[英]Replicate rows with different values in one column
任何人都可以幫助復制R中的行:
我有一個數據集-
ID Study X Y Z Time
1 2 3 4 5 0
2 2 3 4 5 0
3 2 3 4 5 0
也有一個時間向量c(1,1.3,4,5,8,24,34,55,66)
我想用上面的值列表在“ Time
列中用新行復制每一行,例如:
ID Study X Y Z Time
1 2 3 4 5 0
1 2 3 4 5 1
1 2 3 4 5 1.3
1 2 3 4 5 4
這樣的一種方法:
數據:
dt <- read.table(text=c("ID Study X Y Z Time",
"1 2 3 4 5 0",
"2 2 3 4 5 0",
"3 2 3 4 5 0"), header=T)
解:
vect <- list(c(0,1,1.3,4,5,8,24,34,55,66)) #convert the vector to a list
dt$Time <- vect #use that converted list to add as column, it will replace the existing Time column
dt <- tidyr::unnest(dt, Time) #use tidyr::unnest to unnest the column time
或者按照@thelatemail的建議,您可以像這樣使用baseR(使用Base R中的默認矢量化):
newdt <- dt[rep(seq_len(nrow(dt)), each=length(vect)),]
newdt$Time <- vect #We can see the vectorization of values in R here
我在這里有兩個假設:現有的Time變量完全為零,並且您希望頂部的每個ID的時間值為零。
輸出 :
# ID Study X Y Z Time
# 1 1 2 3 4 5 0.0
# 2 1 2 3 4 5 1.0
# 3 1 2 3 4 5 1.3
# 4 1 2 3 4 5 4.0
# 5 1 2 3 4 5 5.0
如果我正確理解了您的問題,則希望使用給定的向量從第二次觀察開始修改時間值。 您可以簡單地使用以下表達式,注意長度以防止意外回收:
df$Time[-1] <- time_vec # alternatively: df$Time[2:n] <- time_vec where n = 10 in this case
數據:
df <- data.frame(
ID = 1:10,
Study = rep(2, 10),
X = rep(3, 10),
Y = rep(4, 10),
Z = rep(5, 10),
Time = rep(0, 10)
)
time_vec <- c(1, 1.3, 4, 5, 8, 24, 34, 55, 66)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.