0

I have a dataset in R organized like so:

             x freq
1 PRODUCT10000    6
2 PRODUCT10001   20
3 PRODUCT10002   11
4 PRODUCT10003    4
5 PRODUCT10004    1
6 PRODUCT10005    2

Then, I have a function like

fun <- function(number, df1, string, df2){NormC <- as.numeric(df1[string, "normc"])
    df2$NormC <- rep(NormC)} 

How can I iterate through my df and insert each value of "x" into the function?

I think the problem is that this part of the function (which has 4 input variables) is structured like so- NormC <- as.numeric(df[string, "normc"])

zsad512
  • 861
  • 3
  • 15
  • 41
  • 1
    What does `fun` do? Depending on how `fun` works, you may not need to iterate. Many operations in R are vectorised, such that you could just call `fun(df$x)` if your function is written a certain way. – duckmayr Nov 17 '17 at 23:58
  • The thing is, the function has 4 input variables... for one of those variables, I want to iterate through the rows of a df- Im having trouble using the rows as string values also... – zsad512 Nov 18 '17 at 14:21
  • In that case, then you will probably get higher quality assistance by editing your question to give a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). In your case, including the definition of `fun`, probably more information on your data since you're talking about needing to deal with at least three other variables in this operation, etc. – duckmayr Nov 18 '17 at 14:26
  • I cannot reproduce the data as I have signed an NDA, but I have tried to edit the question to provide the information you have mentioned. – zsad512 Nov 18 '17 at 14:35

1 Answers1

0

As explained by @duckmayr, you don't need to iterate through column x. Here is an example creating new variable.

df <- read.table(text = "             x freq
1 PRODUCT10000    6
2 PRODUCT10001   20
3 PRODUCT10002   11
4 PRODUCT10003    4
5 PRODUCT10004    1
6 PRODUCT10005    2", header = TRUE)
fun <- function(string){paste0(string, "X")} # example 
# option 1
df$new.col1 <- fun(df$x) # see duckmayr's comment
# option 2
library(data.table)
setDT(df)[, new.col2 := fun(x)]
nghauran
  • 6,648
  • 2
  • 20
  • 29