R:根据数据框另一列中的不同信息合并列 [英] R: Combine columns based on different information in another column of a dataframe

查看:53
本文介绍了R:根据数据框另一列中的不同信息合并列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图为以下数据操纵目的找到一种更简便的方法。数据框是这样的:

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"

对于所有带有 Up标签的行(在 label col中),我将其与对象名称相同的每一行合并,但是带有向下标签。产生的新行(最好是在新表中)应具有一列,该列既包含向上标记行的日期输入,又包含向下标记行的房间。一个示例结果数据框可能看起来像:

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. 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"

请注意,标有 up的一个样本可能有多个相关的向下标记行,我想将所有行都包括在内。我可以先在上下行分开,然后在数据帧中逐行循环,但这会很费时,尤其是当我有数百个对象时。如果您有一些更简单的方法,请告诉我:)

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

这篇关于R:根据数据框另一列中的不同信息合并列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆