简体   繁体   English

在数据上应用函数并在R中获得向量/ df输出?

[英]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). 我有一个函数,为每个var1值分配一个数字分数(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: 我想使用apply like函数来获取一个包含2列的数据框:var1和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. 我曾尝试使用vapply和map_dfr,但它不像我所示的那样工作。 Please advise how to do this. 请告知如何做到这一点。

PS PS

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

Taking help from akrun's solution, this is even simpler 从akrun的解决方案中获得帮助,这更加简单

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. 将矢量转换为data.frame ,然后使用sapply创建新矢量。

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 我们可以通过循环vector (“VAR1”)应用功能( f )得到一个listvector ,设定的名字vector与“VAR1”和使用stack将其转换为一个2列data.frame

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

By default, the stack returns column names as 'ind' and 'values'. 默认情况下, stack将列名称返回为“ind”和“values”。 We could change that to 'var1' and 'score' 我们可以将其更改为'var1'和'得分'

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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