使用 sum(x:y) 从 R 中的现有值创建一个新的 variable/vector
Using sum(x:y) to create a new variable/vector from existing values in R
我在 R 中使用数据框 d:
ID <- c("A","A","A","B","B")
eventcounter <- c(1,2,3,1,2)
numberofevents <- c(3,3,3,2,2)
d <- data.frame(ID, eventcounter, numberofevents)
> d
ID eventcounter numberofevents
1 A 1 3
2 A 2 3
3 A 3 3
4 B 1 2
5 B 2 2
其中 numberofevents
是每个 ID
的 eventcounter
中的最大值。
目前,我正在尝试创建一个附加向量 z <- c(6,6,6,3,3)
。
如果numberofevents == 3
,应该计算sum(1:3)
,等于3 + 2 + 1 = 6
。
如果是numberofevents == 2
,应该计算出sum(1:2)
等同于2 + 1 = 3
。
处理大量数据时,我认为创建这个额外的向量可能会很方便
通过使用 R d$z<-sum(1:d$numberofevents)
中的求和函数,即
sum(1:3) # for the rows 1-3
和
sum(1:2) # for the rows 4-5.
但是,我总是收到这个警告:
Numerical expression has x elements: only the first is used.
你可以试试ave
d$z <- with(d, ave(eventcounter, ID, FUN=sum))
或使用data.table
library(data.table)
setDT(d)[,z:=sum(eventcounter), ID][]
尝试在 R 中使用 apply sapply 或 lapply 函数。
sapply(numberofevents, function(x) sum(1:x))
对我有用。
我在 R 中使用数据框 d:
ID <- c("A","A","A","B","B")
eventcounter <- c(1,2,3,1,2)
numberofevents <- c(3,3,3,2,2)
d <- data.frame(ID, eventcounter, numberofevents)
> d
ID eventcounter numberofevents
1 A 1 3
2 A 2 3
3 A 3 3
4 B 1 2
5 B 2 2
其中 numberofevents
是每个 ID
的 eventcounter
中的最大值。
目前,我正在尝试创建一个附加向量 z <- c(6,6,6,3,3)
。
如果numberofevents == 3
,应该计算sum(1:3)
,等于3 + 2 + 1 = 6
。
如果是numberofevents == 2
,应该计算出sum(1:2)
等同于2 + 1 = 3
。
处理大量数据时,我认为创建这个额外的向量可能会很方便
通过使用 R d$z<-sum(1:d$numberofevents)
中的求和函数,即
sum(1:3) # for the rows 1-3
和
sum(1:2) # for the rows 4-5.
但是,我总是收到这个警告:
Numerical expression has x elements: only the first is used.
你可以试试ave
d$z <- with(d, ave(eventcounter, ID, FUN=sum))
或使用data.table
library(data.table)
setDT(d)[,z:=sum(eventcounter), ID][]
尝试在 R 中使用 apply sapply 或 lapply 函数。
sapply(numberofevents, function(x) sum(1:x))
对我有用。