I have this dataframe (df):
df <- data.frame(Data1 = c(1,3),
Data2 = c(3,9),
Data3 = c(7,2),
Data1Status = c(1,4),
Data2Status = c(2,5),
Data3Status = c(3,6),
NumberOfMaxValue = c(3,2))
Data1 Data2 Data3 Data1Status Data2Status Data3Status NumberOfMaxValue
1 3 7 1 2 3 3
3 9 2 4 5 6 2
And i want do get this new column:
Data1 Data2 Data3 Data1Status Data2Status Data3Status NumberOfMaxValue DataMaxStatus
1 3 7 1 2 3 3 3
3 9 2 4 5 6 2 5
I tried something like this:
DataMaxStatus = df[, as.numeric(df$NumberOfMaxValue) + 3]
, but it didn't work.
EDIT/EXPLANATION:
NumberOfMaxValue is the number of the biggest data (1, 2 or 3)
DataMaxStatus is the status of the greater number between Data1, Data2 e Data3
We can get the corresponding Status
value by creating a matrix of row/column index to subset from Status
columns.
cols <- grep('Status', names(df))
df$DataMaxStatus <- df[cols][cbind(1:nrow(df), df$NumberOfMaxValue)]
df
# Data1 Data2 Data3 Data1Status Data2Status Data3Status NumberOfMaxValue DataMaxStatus
#1 1 3 7 1 2 3 3 3
#2 3 9 2 4 5 6 2 5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.