如何为R中的列的每个值运行一个函数

时间:2018-10-30 00:25:11

标签: r loops dplyr

我想基于另一个类型为character的列在分数列上运行函数。我想缩放此函数,以便它可以获取列的名称并为每个元素的结果提供一个数组。

当前,我正在手动进行操作,这意味着我可以看到唯一值是什么,然后运行该函数,最后附加输出。参见下面的简单示例:

#data
df<-data.frame(category1 = sample(c("M", "F"),100,replace=TRUE), 
            category2 = sample(c("A", "B", "C"),100,replace=TRUE), 
            score = runif(100))

#identifying the elements
table(df$category1)
# F  M 
#43 57
#running the function
append(
      sum(df$score[df$category1 == 'M']),
      sum(df$score[df$category1 == 'F'])
)

理想情况下,我会得到这个:

f <- function(dataframe, score_Column, categoriaal_column){
     identify the levels
     run the function for each level
     create a table with each level and its corresponding output
}

1 个答案:

答案 0 :(得分:1)

如果期望的输出为count,我们可以使用summarized来做到这一点

library(dplyr)
df %>%
   count(category1)

如果需要创建列,请在mutate'category1'之后使用group_by

df %>%
   group_by(category1) %>%
   mutate(n = n())