Reputation: 1850
The variable Jaehrlichkeit
is basically a factor with 3 levels: HQ30
, HQ100
, HQ300
. I want R to read Jaehrlichkeit
. If Jaehrlichkeit
= HQ30
, the copy the value from the column intHQ30
in the correponding row and paste it in the newly created column Intensitaet
. Repeat this for HQ100
and HQ300
.
I was trying to combine the mutate
function with nested ifelse
but keep getting errors. Can please someone help me out? or maybe suggest an easier solution?
Upvotes: 1
Views: 69
Reputation: 12937
Since Jaehrlichkeit
is of type factor, you could do this vectorized:
r <- sub1[,match(paste0("int", levels(sub1$Jaehrlichkeit)), names(sub1))]
sub1$Intensitaet <- r[cbind(seq(nrow(r)), as.numeric(sub1$Jaehrlichkeit))]
intHQ100
, intHQ30
and intHQ300
in your data frame in the order of levels(sub1$Jaehrlichkeit)
.Intensitaet
column.Upvotes: 0
Reputation: 51582
Another option would be to split, and apply, i.e.
do.call(rbind, lapply(split(df, df$Jaehrlichkeit), function(i) {
i$Intensitaet <- i[[grep(i$Jaehrlichkeit[1], names(i))]]; i
}))
Upvotes: 1
Reputation: 886948
We can do this with row/column
indexing. Get the names of the columns that start with 'int' followed by 'HQ' and some numbers (\\d+
) using grep
. Then, get the column index for each row by match
ing the 'Jaehrlichkeit' with the substring of 'v1', cbind
with the row sequence and use that to extract the values from the intHQ
columns and assign it to create the 'Intensitaet'
v1 <- grep("^intHQ\\d+", names(sub1), value = TRUE)
sub1$Intensitaet <- sub1[v1][cbind(1:nrow(sub1),
match(sub1$Jaehrlichkeit, sub("int", "", v1)))]
Upvotes: 1