R如何根据另一个变量添加行,然后从宽格式转换为长格式
我想分两个步骤重组我的数据框架。
原始数据集:
structure(list(ID = c("1", "2", "3", "4", "5", "6"), Type = c("A",
"B", "B", "A", "A", "C"), A_Var1 = c("Yes", "None", "None", "Yes",
"None", "None"), A_Var2 = c("Yes", "None", "None", "Yes", "Yes",
"None"), A_Var3 = c("Yes", "None", "None", "Yes", "Yes", "Yes"
), B_Var1 = c("NA", "None", "None", "NA", "NA", "None"), B_Var2 = c("NA",
"None", "None", "NA", "NA", "Yes"), B_Var3 = c("NA", "None",
"None", "NA", "NA", "Yes")), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
首先,我希望根据 type 的顺序顺序为每个 id 添加新行。数据框架中有3种类型,并且顺序为a,b,c。对于每个 id ,如果我看到类型B,我想添加一个使用相同 id 但上面键入A的行;如果我看到了C型,那么我将添加两个具有相同ID的行,但在上方键入A和类型B。
其次,我希望在步骤1之后将数据框架从宽格式转换为长格式。因此,我将 var1 , var2 , var3 填充到相应的类型中。
其他数据集:
structure(list(ID = c("1", "2", "2", "3", "3", "4", "5", "6",
"6", "6"), Type = c("A", "A", "B", "A", "B", "A", "A", "A", "B",
"C"), Var1 = c("Yes", "None", "None", "None", "None", "Yes",
"None", "None", "None", NA), Var2 = c("Yes", "None", "None",
"None", "None", "Yes", "Yes", "None", "Yes", NA), Var3 = c("Yes",
"None", "None", "None", "None", "Yes", "Yes", "Yes", "Yes", NA
)), row.names = c(NA, -10L), class = "data.frame")
我很难弄清楚如何以一个不错的顺序完成这两个步骤。感谢任何评论!
I would like to restructure my data frame in two steps.
Original data set:
structure(list(ID = c("1", "2", "3", "4", "5", "6"), Type = c("A",
"B", "B", "A", "A", "C"), A_Var1 = c("Yes", "None", "None", "Yes",
"None", "None"), A_Var2 = c("Yes", "None", "None", "Yes", "Yes",
"None"), A_Var3 = c("Yes", "None", "None", "Yes", "Yes", "Yes"
), B_Var1 = c("NA", "None", "None", "NA", "NA", "None"), B_Var2 = c("NA",
"None", "None", "NA", "NA", "Yes"), B_Var3 = c("NA", "None",
"None", "NA", "NA", "Yes")), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
First, I am hoping to add new rows for each ID based on the sequential order of Type. There are 3 types in the data frame, and the order is A,B,C. For each ID, if I see type B, I would like to add a row with the same ID but type A above; if I see type C, then I will add two rows with same ID but type A and type B above.
Second, I am hoping to transform the data frame after step 1 from a wide format to a long format. So I fill Var1, Var2, Var3 to its corresponding type.
Excepted data set:
structure(list(ID = c("1", "2", "2", "3", "3", "4", "5", "6",
"6", "6"), Type = c("A", "A", "B", "A", "B", "A", "A", "A", "B",
"C"), Var1 = c("Yes", "None", "None", "None", "None", "Yes",
"None", "None", "None", NA), Var2 = c("Yes", "None", "None",
"None", "None", "Yes", "Yes", "None", "Yes", NA), Var3 = c("Yes",
"None", "None", "None", "None", "Yes", "Yes", "Yes", "Yes", NA
)), row.names = c(NA, -10L), class = "data.frame")
I have a hard time figuring out how to accomplish both steps in a nice order. Would appreciate any comment!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用以下代码:
Use the following code: