[英]R: Combine columns based on different information in another column of a dataframe
I'm trying to find an easier way for the following purpose of data manipulation. 我试图为以下数据操纵目的找到一种更简便的方法。 The dataframe is like this:
数据框是这样的:
"object" "Date_In" "Date_out" "label" "room" "test"
"1" "LEU_A" 6 9 "Up" "11z" "c"
"2" "LEU_A" 1 10 "Down" "14x" "c"
"3" "LEU_B" 6 8 "Up" "11z" "a1"
"4" "LEU_B" 10 13 "Down" "14x" "a1"
"5" "ALL_A" 7 8 "Up" "11z" "c"
"6" "ALL_A" 1 26 "Down" "1g" "c"
"7" "CLMIA_A" 5 15 "Up" "11z" "a2"
"8" "CLMIA_A" 10 10 "Down" "14x" "a2"
"9" "CLMIA_A" 10 12 "Down" "13w" "a2"
For all rows with "Up" label (in the "label" col), I will combine it with each of the rows, which has same object name, but with "Down" label. 对于所有带有“ Up”标签的行(在“ label”列中),我将其与对象名称相同但带有“ Down”标签的每一行合并。 The resulting new row (preferably in a new table) should have a column containing both "Date In" from the up-labeled row, and "Room" from the down-labeled row.
产生的新行(最好是在新表中)应具有一列,其中既包含向上标记行的“日期输入”,又包含向下标记行的“房间”。 A sample result dataframe can look like:
样本结果数据框如下所示:
"object" "Date_In_Room"
"1" "LEU_A" "6_14x"
"2" "LEU_B" "6_14x"
"3" "ALL_A" "7_1g"
"4" "CLMIA_A" "5_14x"
"5" "CLMIA_A" "5_13w"
Note that it is possible for one sample labeled with "up" to have more than one related "down" labeled rows, and I'd like to include all of them. 请注意,一个标有“上”的样本可能有多个相关的“下”标有行,我想将所有这些都包括在内。 I could do it by first separate up and down rows, and then looping row by row within the dataframe, but that can be time-consuming, especially when I have hundreds of objects.
我可以先在上下行分开,然后在数据帧中逐行循环,但这会很费时,尤其是当我有数百个对象时。 Please let me know if you have some easier methods:)
如果您有一些简单的方法,请告诉我:)
Thanks a lot for reading. 非常感谢您的阅读。 I appreciate your help.
我感谢您的帮助。
Helene 海伦
library(data.table)
DT <- as.data.table(your_data_frame)
RESULTS <- DT[, list(Date_In[label=="Up"], room[label=="Down"]), keyby=object]
RESULTS
object V1 V2
1: ALL_A 7 1g
2: CLMIA_A 5 14x
3: CLMIA_A 5 13w
4: LEU_A 6 14x
5: LEU_B 6 14x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.