我有两个 Dataframe ,并希望完成一个基于另一个。第一个 Dataframe 称为df1,有100列,A,B,C,D和c(5:100)。第二个 Dataframe 称为df2,是完全相同的,但列c(5:100)有一个不同的名称,并没有在那里的值。现在为每个唯一的值在列A,看看df1,在列D中,它是“内部”,它的值是“1”在列c(5:100),然后把“I”在 Dataframe 称为“df2”列c(5:100),如果0把“O”。我有一个例子给你,想象第一个 Dataframe 是像df1,我想有df2作为结果。
df1 <- structure(list(A=c("A_1_01", "A_1_01", "A_1_01"), B=c("A", "A", "A"), C=c("1", "1", "1"), D=c("inside", "eating", "sleeping"), "1"=c("1","1","0"), "2"=c("1","0","0"), "3"=c("0","0","1"), "4"=c("0","1","1")), class= "data.frame", row.names = c(NA,-3L))
df2<- structure(list(A=c("A_1_01", "A_1_01", "A_1_01"), B=c("A", "A", "A"), C=c("1", "1", "1"), D=c("inside", "eating", "sleeping"), "1"=c("1","1","0"), "2"=c("1","0","0"), "3"=c("0","0","1"), "4"=c("0","1","1"), "1_Location"=c("I","I", "I"), "2_Location"=c("I","I", "I"), "3_Location"=c("O","O", "O"), "4_Location"=c("O","O", "O")), class= "data.frame", row.names = c(NA,-3L))
我怎么用R来做这个呢?
谢谢大家,现在我该如何将列转换为行,以获得df3中所需的结构:
df3<- structure(list(H=c("1","2","3","4","1","2","3","4","1","2","3","4"),
A=c("A_1_01", "A_1_01", "A_1_01","A_1_01", "A_1_01",
"A_1_01","A_1_01", "A_1_01", "A_1_01","A_1_01",
"A_1_01", "A_1_01"),
B=c("A", "A", "A","A", "A", "A","A", "A", "A","A", "A", "A"),
C=c("1", "1", "1","1", "1", "1","1", "1", "1","1", "1", "1"),
D=c("inside","inside","inside","inside",
"eating","eating","eating","eating",
"sleeping","sleeping","sleeping","sleeping"),
Value=c(1,1,0,0,1,0,0,1,0,0,1,1),
Location=c("I","I","O","O","I","I","O","O","I","I","O","O")),
class= "data.frame", row.names = c(NA,-12L))
3条答案
按热度按时间bejyjqdl1#
您可以在所选列上使用
ifelse
来创建df2
:xzv2uavs2#
您可以从
df1
创建df2
,如下所示。(注意,如果df2
实际上是一个不同的框架,其列数1:100与df1
不同[在您的示例中看起来是相同的],只需将df2
替换为内连接中的第一个框架)输出:
xqnpmsa83#
使用
if/else