[英]data manipulation for data.frame based on column index
我有一個data.frame
如下
A <- sample(1:10,5)
B <- sample(11:20, 5)
C <- sample(21:30, 5)
index <- sample(1:3,5, replace=TRUE)
data <- data.frame(A,B,C,index)
> data
A B C index
1 9 17 30 3
2 10 15 26 2
3 2 19 23 2
4 3 13 29 2
5 8 12 25 2
我想要的輸出是
> data$output <- c(30,15,19,13,12)
> data
A B C index output
1 9 17 30 3 30
2 10 15 26 2 15
3 2 19 23 2 19
4 3 13 29 2 13
5 8 12 25 2 12
這個想法是索引指示我要提取的列數。 例如對於第二行,索引為2,則輸出應為B:15。
避免使用例如循環的巧妙方法是使用矩陣來對數據幀進行子集化。 首先生成一個矩陣,該矩陣指定要提取的“單元”:
m<-matrix(ncol=2, data=c(as.numeric(rownames(data)), data$index))
現在矩陣m必須具有列,第一個用於數據幀的行索引,第二個用於數據幀的列索引。 請注意,如果行名不是按升序排列,則可能需要相應地調整as.numeric(rownames(data))
部分。 但是此解決方案適用於示例數據。
然后使用此矩陣簡單地將數據幀設置為子集:
data[m]
應該產生正確的結果。 然后可以將其分配給數據框的輸出列:
data$output<-data[m]
這記錄在[運算符的幫助文件中。 參見?"["
,特別注意“當用[單個參數索引數組索引時,我可以是一個矩陣,其列數與x的維數相同;然后,結果是一個向量,其中每個元素對應於索引集一排。”。
data.table
方法(應該更有效)
library(data.table)
setDT(data)[, output := .SD[, index, with = F], by = index]
# A B C index output
# 1: 9 17 30 3 30
# 2: 10 15 26 2 15
# 3: 2 19 23 2 19
# 4: 3 13 29 2 13
# 5: 8 12 25 2 12
要么,
data$output <- t(data[,-4])[data$index+(0:4)*3] #0:4 denotes 1-(1:nrow(data));
#3 is ncol(data[,-4])
data$output
#[1] 30 15 19 13 12
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.