【发布时间】:2021-01-13 15:54:32
【问题描述】:
我有一个数据框,其中包含按站点和 ID 分组的数据。我想创建一个新列,其逻辑值指示在每个站点中,id 是否与前一行中的角度匹配。
other.dat <- c(1:12)
site <- c(rep(1,6), rep(2,6))
id <- c(1.1,1.2,1.3,1.1,1.2,1.3,2.1,2.2,2.3,2.1,2.2,2.3)
angle <- c(65,250,150,65,250,150,0,240,150,345,205,100)
data.frame(other.dat,site,id,angle)
other.dat site id angle
1 1 1 1.1 65
2 2 1 1.2 250
3 3 1 1.3 150
4 4 1 1.1 65
5 5 1 1.2 250
6 6 1 1.3 150
7 7 2 2.1 0
8 8 2 2.2 240
9 9 2 2.3 150
10 10 2 2.1 345
11 11 2 2.2 205
12 12 2 2.3 100
与上一个问题中给出的示例不同 (Identify if a value is repeated or not by groups in R),对于站点而言,角度不需要是唯一的,逻辑变量为 TRUE 并且第一个唯一 id 将始终为 TRUE。例如:
other.dat <- c(1:12)
site <- c(rep(1,6), rep(2,6))
id <- c(1.1,1.2,1.3,1.1,1.2,1.3,2.1,2.2,2.3,2.1,2.2,2.3)
angle <- c(65,250,150,65,250,150,0,240,150,345,205,100)
same.angle <- c(T,T,T,T,T,T,T,T,T,F,F,F)
data.frame(other.dat,site,id,angle, same.angle)
other.dat site id angle same.angle
1 1 1 1.1 65 TRUE
2 2 1 1.2 250 TRUE
3 3 1 1.3 150 TRUE
4 4 1 1.1 65 TRUE
5 5 1 1.2 250 TRUE
6 6 1 1.3 150 TRUE
7 7 2 2.1 0 TRUE
8 8 2 2.2 240 TRUE
9 9 2 2.3 150 TRUE
10 10 2 2.1 345 FALSE
11 11 2 2.2 205 FALSE
12 12 2 2.3 100 FALSE
我尝试过使用df <- within(df, same.angle <- as.logical(angle, id, FUN = function(x) length(unique(x))==1))),但由于我还不明白的原因,只有第 7 行返回为“FALSE”。
提前感谢您的帮助!
【问题讨论】:
标签: r database logical-operators