Subsetting with for function in R

Viewed 42

Trying to use a function to get the means of multiple different subsets of columns and add them as new columns. DMcomponents defines a character vector. Each entry in this vector is defined by its own character vector with column names.

for (i in DMcomponents){
  DMData["i"] <- rowMeans(DMData[c(i)])
}

In my mind, this should work, but I get this error:

Error in `[.data.frame`(DMData, c(i)) : undefined columns selected

I'm guessing it has something to do with how the vector is "pasted" into the subset argument? Thanks

id <- c(1, 2, 3)
a <- c(4, 4, 4)
b <- c(6, 6, 6)
c <- c(8, 8, 8)
d <- c(10, 10, 10)

abcd <- data.frame(id, a, b, c, d)


DMcomponents <- c("ab", "cd")

ab <- c("a", "b")
cd <- c("c", "d")

ab <- c(5, 5, 5)
cd <- c(9, 9, 9)

desired result:

abcd_end <- data.frame(id, a, b, c, d, ab, cd)
1 Answers

We don't need to quote

lst1 <- mget(DMcomponents)

 for (nm in names(lst1)){
    abcd[nm] <- rowMeans(abcd[lst1[[nm]]])
  }

abcd
#  id a b c  d ab cd
#1  1 4 6 8 10  5  9
#2  2 4 6 8 10  5  9
#3  3 4 6 8 10  5  9

data

id <- c(1, 2, 3)
a <- c(4, 4, 4)
b <- c(6, 6, 6)
c <- c(8, 8, 8)
d <- c(10, 10, 10)

abcd <- data.frame(id, a, b, c, d)
DMcomponents <- c("ab", "cd")
ab <- c("a", "b")
cd <- c("c", "d")
Related