在循环期间使用rbind添加0值
我在为向小数据集添加行而正确编写循环时遇到问题 假设我有以下名为“颜色”的数据框: 现在我需要的是为每列添加0个值,以便所有组都有每种颜色,也就是它应该是这样的:在循环期间使用rbind添加0值,r,loops,grouping,sapply,rbind,R,Loops,Grouping,Sapply,Rbind,我在为向小数据集添加行而正确编写循环时遇到问题 假设我有以下名为“颜色”的数据框: 现在我需要的是为每列添加0个值,以便所有组都有每种颜色,也就是它应该是这样的: color count group Blue 3 1 Blue 2 2 Red 2 2 Green 1 1 Red 0 1 Green 0 2 我试图做的最接近我想要的解决方案的事情是: co
color count group
Blue 3 1
Blue 2 2
Red 2 2
Green 1 1
Red 0 1
Green 0 2
我试图做的最接近我想要的解决方案的事情是:
color.u <- unique(colors$color)
color.z<- function(x){
if(x %in% colors$color[colors$group == "1"] == F ) {
rbind(colors, c(x, 0, "1"))
}
if(x %in% colors$color[colors$group == "2"] == F ) {
rbind(colors, c(x, 0, "2"))
}
}
sapply(color.u, function(x) color.z(x))
color.u使用tidyr::complete()
完成(数据=df,
颜色=级别(颜色),组=级别(组),
填充=列表(计数=0))
使用tidyr::complete()
:
完成(数据=df,
颜色=级别(颜色),组=级别(组),
填充=列表(计数=0))
此tidyverse
解决方案使用数据框中的color
和group
的每种组合创建一个完整的
数据集。如果未指定fill=
,默认值将使用NA
值填充count
。使用命名列表list(count=0)
告诉tidyr
用零填充
此tidyverse
解决方案使用数据框中的color
和group
的每种组合创建一个完整的
数据集。如果未指定fill=
,默认值将使用NA
值填充count
。使用命名列表list(count=0)
告诉tidyr
用零填充。使用基数R
df1 <- structure(list(color = c("Blue", "Blue", "Red", "Green"),
count = c(3, 2, 2, 1),
group = c(1L, 2L, 2L, 1L)),
row.names = c(NA, -4L),
class = "data.frame")
df2 <- expand.grid(color = unique(df1$color), group = unique(df1$group))
df2 <- merge(df2, df1, all = TRUE)
df2$count[is.na(df2$count)] <- 0
color group count
1 Blue 1 3
2 Blue 2 2
3 Red 1 0
4 Red 2 2
5 Green 1 1
6 Green 2 0
df1使用基本R
df1 <- structure(list(color = c("Blue", "Blue", "Red", "Green"),
count = c(3, 2, 2, 1),
group = c(1L, 2L, 2L, 1L)),
row.names = c(NA, -4L),
class = "data.frame")
df2 <- expand.grid(color = unique(df1$color), group = unique(df1$group))
df2 <- merge(df2, df1, all = TRUE)
df2$count[is.na(df2$count)] <- 0
color group count
1 Blue 1 3
2 Blue 2 2
3 Red 1 0
4 Red 2 2
5 Green 1 1
6 Green 2 0
df1你必须使用循环吗?我想不是,sapply的工作原理类似于循环,但除此之外,我认为我不需要for循环或类似的东西。你必须使用循环吗?我想不是,sapply的工作原理类似于循环,但除此之外,我认为我不需要for循环或类似的东西。我认为你赢了我几秒钟@布莱恩,哈哈,我想你赢了我几秒钟@布莱恩:哈哈
df1 <- structure(list(color = c("Blue", "Blue", "Red", "Green"),
count = c(3, 2, 2, 1),
group = c(1L, 2L, 2L, 1L)),
row.names = c(NA, -4L),
class = "data.frame")
df2 <- expand.grid(color = unique(df1$color), group = unique(df1$group))
df2 <- merge(df2, df1, all = TRUE)
df2$count[is.na(df2$count)] <- 0
color group count
1 Blue 1 3
2 Blue 2 2
3 Red 1 0
4 Red 2 2
5 Green 1 1
6 Green 2 0