具有列ID,列类别,列成本和列颜色的数据框。
这是数据帧df
library(dplyr)
id <- c(1, 1, 1, 2, 2, 3, 1)
category <- (c("V", "V", "V", "W", "W", "W", "W"))
cost <- c(10, 15, 5, 2, 14, 20, 3)
colour <- c("red", "green", "red", "green", "blue","blue","blue")
df <- data.frame(id, category, cost, colour)
df$category <- as.character(df$category)
df
id category cost colour
1 V 10 red
1 V 15 green
1 V 5 red
2 W 2 green
2 W 14 blue
3 W 20 blue
1 W 3 blue
这是df的格式
'data.frame': 7 obs. of 4 variables:
$ id : num 1 1 1 2 2 3 1
$ category : chr "V" "V" "V" "W" ...
$ cost: num 10 15 5 2 14 20 3
$ colour : Factor w/ 3 levels "blue","green",..: 3 2 3 2 1 1 1
我想要一个新的数据帧df_new,并为每个id提供频率(freq),条目等于W(category_W)的类别条目数,条目等于V的类别条目数(category_V ),类别条目为W(cost_W)的每个id的总成本,类别条目为V(cost_V)的每个id的总成本,以及每个唯一ID的每个颜色条目的数量(col_red,col_green,col_blue) )。 输出应该看起来像
id freq category_W category_V cost_W cost_V col_red col_green col_blue
1 4 1 3 3 30 2 1 1
2 2 2 16 1 1
3 1 1 20 1
我尝试了以下方法 - 但它没有效果。
df_new <- group_by(df, id) %>% summarize(freq = count(id), category_W = count(category == "W", na.rm=TRUE), category_V = count(category == "V", na.rm=TRUE), col_red = count(colour == "red", na.rm=TRUE), col_green = count(colour == "green", na.rm=TRUE), col_blue = count(colour == "blue", na.rm=TRUE))
我不知道如何插入cost_W和cost_V的条件。 我收到错误:length(rows)== 1不为TRUE 非常感谢提前!
答案 0 :(得分:0)
嗯,你快到了。
您可以利用逻辑值在算术运算中转换为0和1的事实。因此,当您对它们求和时,您将获得逻辑子句测试的特定值的计数。
您可以使用相同的属性来计算成本。只需将逻辑子句与成本变量相乘即可。如果类别与您的兴趣匹配,则将其相加,否则,将其减少为0
df_new <-
group_by(df, id) %>% summarize(
freq = n(),
category_W = sum(category == "W", na.rm = TRUE),
category_V = sum(category == "V", na.rm = TRUE),
cost_W = sum((category == "W") * cost, na.rm = TRUE),
cost_V = sum((category == "V") * cost, na.rm = TRUE),
col_red = sum(colour == "red", na.rm = TRUE),
col_green = sum(colour == "green", na.rm = TRUE),
col_blue = sum(colour == "blue", na.rm = TRUE)
)