R:关于表格重塑的问题
我有以下数据框:R:关于表格重塑的问题,r,dataframe,R,Dataframe,我有以下数据框: id,property1,property2,property3 1,1,0,0 2,1,1,0 3,0,0,1 4,1,1,1 d.f <- structure(list(id = 1:4, property1 = c(1L, 1L, 0L, 1L), property2 = c(0L, 1L, 0L, 1L), property3 = c(0L, 0L, 1L, 1L)), .Names = c("id", "property1", "propert
id,property1,property2,property3
1,1,0,0
2,1,1,0
3,0,0,1
4,1,1,1
d.f <- structure(list(id = 1:4, property1 = c(1L, 1L, 0L, 1L), property2 = c(0L,
1L, 0L, 1L), property3 = c(0L, 0L, 1L, 1L)), .Names = c("id",
"property1", "property2", "property3"), class = "data.frame", row.names = c(NA,
-4L))
id,properties_list
1,property1
2,property1, property2
3,property3
4,property1, property2, property3
也许有一些像融化或重塑这样的奇特选择?这根本不是重塑,真的。用浆糊
这根本不是重塑,真的。用浆糊
这实际上并不是一个适当的数据帧,它必然具有具有相同条目数的所有行,因此正确的答案是您可能需要一个列表。如果这不是您真正想要的,请尝试以下方法:
dfrm[-1] <- t( apply(dfrm[-1], 1, function(x) ifelse(x, names(x), "") ) )
dfrm
id property1 property2 property3
1 1 property1
2 2 property1 property2
3 3 property3
4 4 property1 property2 property3
您需要t,因为apply行操作会因为R施加的列主顺序而转置它们的结果
如果您确实想要列表版本,那么有一种方法:
prop_list <- apply(dfrm[-1], 1, function(x) c(names(x)[ as.logical(x)] ) )
names(prop_list) <- dfrm[,1]
prop_list
$`1`
[1] "property1"
$`2`
[1] "property1" "property2"
$`3`
[1] "property3"
$`4`
[1] "property1" "property2" "property3"
这实际上并不是一个适当的数据帧,它必然具有具有相同条目数的所有行,因此正确的答案是您可能需要一个列表。如果这不是您真正想要的,请尝试以下方法:
dfrm[-1] <- t( apply(dfrm[-1], 1, function(x) ifelse(x, names(x), "") ) )
dfrm
id property1 property2 property3
1 1 property1
2 2 property1 property2
3 3 property3
4 4 property1 property2 property3
您需要t,因为apply行操作会因为R施加的列主顺序而转置它们的结果
如果您确实想要列表版本,那么有一种方法:
prop_list <- apply(dfrm[-1], 1, function(x) c(names(x)[ as.logical(x)] ) )
names(prop_list) <- dfrm[,1]
prop_list
$`1`
[1] "property1"
$`2`
[1] "property1" "property2"
$`3`
[1] "property3"
$`4`
[1] "property1" "property2" "property3"
此解决方案假设您正在寻找一个数据帧,该数据帧类似于gsk3如何解释将属性粘贴在一起的问题,但必须避免for循环,因为这就是我们使用R的方式:
property_list <- apply(d.f[,-1],1,
FUN=function(x,nms){paste(nms[as.logical(x)],collapse=",")},
nms=colnames(d.f)[-1])
as.data.frame(cbind(d.f$id,property_list))
V1 property_list
1 1 property1
2 2 property1,property2
3 3 property3
4 4 property1,property2,property3
此解决方案假设您正在寻找一个数据帧,该数据帧类似于gsk3如何解释将属性粘贴在一起的问题,但必须避免for循环,因为这就是我们使用R的方式:
property_list <- apply(d.f[,-1],1,
FUN=function(x,nms){paste(nms[as.logical(x)],collapse=",")},
nms=colnames(d.f)[-1])
as.data.frame(cbind(d.f$id,property_list))
V1 property_list
1 1 property1
2 2 property1,property2
3 3 property3
4 4 property1,property2,property3
我不是有意要避免循环。。。但是是的-如果你试图避免循环,你会学到更多的R:我不是故意要避免循环。。。但是是的-如果你试图避免循环,你会学到更多的R: