简体   繁体   中英

How to apply a function on a specific column in the data frame using R?

R newbie is here, and I'm tying to figure out how to apply a function on every row in a data frame and add the result to the data frame. To be more precise, I'm providing an example below.

So say I have:

n = c(2, 3, 5) 
s = c("aa", "bb", "cc") 
b = c(TRUE, FALSE, TRUE) 
df = data.frame(n, s, b)
df

   n  s     b
1  2 aa  TRUE
2  3 bb FALSE
3  5 cc  TRUE

my dummy function is:

dummyfunc <- function(x)
{  
  return (x*2)
}

my goal is to apply dummyfunc on the column n and to get the following result:

   n   s     b
1  4  aa  TRUE
2  6  bb FALSE
3  10 cc  TRUE

I learned that apply can do that but I couldn't figure it out how to use it on each row.

您不需要套用,只需运行df$n <- dummyfunc(df$n)

You can use transform

> (df2 <- transform(df, n=dummyfunc(n)))
   n  s     b
1  4 aa  TRUE
2  6 bb FALSE
3 10 cc  TRUE

within is also valid

> (df3 <- within(df, n <- dummyfunc(n)))

to answer your question on using apply, try this

df <-apply(df["n"],1, function(x) x *2)

The 1 is the value given to margin, read ?apply for more details. the 1 is telling apply to "apply" the function to each row. if instead you wanted to apply it to columns, you would use 2.

though I suggest using transform() (as suggested above), as it is better suited for working with data.frames just remember to assign the result of transform() back to df or another data.frame

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM