G.P.
G.P.

Reputation: 75

Transform elements in column with the column name as argument

I'm trying to modify the data in a data set based on a vector of columns to change. That way I could factorize the treatment based on a config file which would have the list of columns to change as a variable.

Ideally, I'd like to be able to use ddply like that :

column <- "var2"
df <- ddply(df, .(), transform, column = func(column))

The output would be the same dataframe but in the column "B", each letter would have an "A" added behind it

Which would change each element of the column var2 by the element through func (func here is used to trim a chr in a particular way). I've tried several solutions, like :

df[do.call(func, df[,column]), ]

which doesn't accept the df[,column] as argument (not a list), or

param = c("var1", "var2")
for(p in param){
    df <- df[func(df[,p]),]
}

which destroys the other data, or

df[, column] <- lapply(df[, column], func)

Which doesn't work because it takes the whole column as argument instead of changing each element 1 by 1. I'm kinda out of ideas on how to make this treatment more automatic.

Example :

df <- data.frame(A=1:10, B=letters[2:11])
colname <- "B"
addA <- function(text) { paste0(text, "A") }

And I would like to do something like this :

df <- ddply(df, .(), transform, colname = addA(colname))

Though if the solution does not use ddply, it's not an issue, it's just what I'm the most used to

Upvotes: 1

Views: 56

Answers (1)

aosmith
aosmith

Reputation: 36076

You could use mutate_at from package dplyr for this.

library(dplyr)

mutate_at(df, colname, addA)

    A  B
1   1 bA
2   2 cA
3   3 dA
4   4 eA
5   5 fA
6   6 gA
7   7 hA
8   8 iA
9   9 jA
10 10 kA

Upvotes: 1

Related Questions