![](/img/trans.png)
[英]Can I create a new numerical variable using dplyr and <= and >= operators to subset values from an existing 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
是eventcounter
中每個ID
的eventcounter
。
目前,我正在嘗試創建一個附加向量z <- c(6,6,6,3,3)
。 如果事件數numberofevents == 3
,則應該計算sum(1:3)
, sum(1:3)
3 + 2 + 1 = 6
。
如果事件數numberofevents == 2
,則應該計算sum(1:2)
2 + 1 = 3
。
使用大量數據,我認為通過使用R d$z<-sum(1:d$numberofevents)
的sum函數來創建此附加向量可能比較方便。
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))
這個對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.