【发布时间】:2018-10-30 00:25:10
【问题描述】:
我想在基于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
}
【问题讨论】:
-
你需要
library(dplyr);df %>% group_by(category1, category2) %>% mutate(n = n()) -
你是对的!我想我把它复杂化了!我是根据您的评论这样做的:
library(dplyr);df %>% group_by(category1) %>% transmute(n = n()) %>% unique() %>% as.data.frame