简体   繁体   中英

Apply function on data and get vector/df output in R?

I have the following date:

var1 <- c("a", "b", "c", "d", "e")

I have a function that assigns each var1 value a numeric score (0-3).

    f(a) --> 2
    f(b) --> 1 

etc...

I want to use apply like function to get a data frame with 2 columns: var1 and score:

var1  score
a     1
b     0
c     3
d     3
e     2
f     1

I have tried to use vapply and map_dfr but it doesn't work like I have shown. Please advise how to do this.

PS

For map_dfr: Error: cannot convert object to a data frame

Taking help from akrun's solution, this is even simpler

f <- function(x) sample(0:3, 1)
var1 <- c("a", "b", "c", "d", "e")

data.frame(cbind(Var1 = var1, Score = lapply(var1,f)))

  Var1 Score
1    a     0
2    b     2
3    c     0
4    d     1
5    e     3

Convert your vector to data.frame , then use sapply to create the new vector.

df1 <- as.data.frame(var1)
df1$test <- sapply(df1$var1, function(x) if (x=="a") 1 else 0) 


  var1 test
1    a    1
2    b    0
3    c    0
4    d    0
5    e    0

 str(df1)
'data.frame':   5 obs. of  2 variables:
 $ var1: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
 $ test: num  1 0 0 0 0

We can loop through the vector ('var1') apply the function ( f ) to get a list of vector , set the names of the vector with the 'var1' and use stack to convert it to a 2 column data.frame

stack(setNames(lapply(var1, f), var1))[2:1]

By default, the stack returns column names as 'ind' and 'values'. We could change that to 'var1' and 'score'

setNames(stack(setNames(lapply(var1, f), var1))[2:1], c('var1', 'score'))

data

f <- function(x) sample(0:3, 1)
var1 <- c("a", "b", "c", "d", "e")

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