Nneka
Nneka

Reputation: 1850

Adding a column based on values of other columns

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

Answers (3)

989
989

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))]
  • First you get the value of columns intHQ100, intHQ30 and intHQ300 in your data frame in the order of levels(sub1$Jaehrlichkeit).
  • Then you generate the indices and create the Intensitaet column.

Upvotes: 0

Sotos
Sotos

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

akrun
akrun

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 matching 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

Related Questions