我有一张下表,该表代表一个孩子,他的兄弟姐妹以及他们的下属情况。资源ID代表它们放置在一起的房子。
child_id|sibling_id|case_id|resource_id
1 8 123 12856
1 9 123 12856
3 11 321 12555
4 12 323 10987
4 13 323 10956
6 14 156 10554
6 15 156 10554
10 16 156 10553
10 17 145 18986
10 18 145 18986
我想创建一个新列placed_together
,该列显示根据其yes
放置在一起的那些孩子的no
或case_id
。所以我的结果应该像这样
child_id|sibling_id|case_id|resource_id|placed_together
1 8 123 12856 Yes
1 9 123 12856 Yes
3 11 321 12555 No
4 12 323 10987 No
4 13 323 10956 No
6 14 156 10554 No
6 15 156 10554 No
10 16 156 10553 No
10 17 145 18986 Yes
10 18 145 18986 Yes
任何帮助将不胜感激。我不知道如何根据这些条件创建if语句,因为case_id对于一个组可以是相同的,但是对于一个孩子来说,它们的资源ID可以是不同的。
答案 0 :(得分:1)
可能使用tidyverse
:
library(tidyverse)
df %>%
group_by(case_id) %>%
mutate(placedTogether = if_else(n()>1 &length(unique(child_id))==1 &
length(unique(resource_id))==1, "Yes", "No"))
# A tibble: 10 x 5
# Groups: case_id [5]
child_id sibling_id case_id resource_id placedTogether
<int> <int> <int> <int> <chr>
1 1 8 123 12856 Yes
2 1 9 123 12856 Yes
3 3 11 321 12555 No
4 4 12 323 10987 No
5 4 13 323 10956 No
6 6 14 156 10554 No
7 6 15 156 10554 No
8 10 16 156 10553 No
9 10 17 145 18986 Yes
10 10 18 145 18986 Yes
答案 1 :(得分:0)
假设您的数据框名为 df ,则可以执行以下操作:
# create a function that defines if a child is placed together
IsPlacedTogether = function(x, y) ifelse(sum(x == y) > 1, 'Yes', 'No')
# apply this function to every child in your data
df$placed_together = sapply(df$case_id, IsPlacedTogether, df$case_id)