Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R code that applies a function to subsection of variables of a dataframe and saves it to original dataframe

Tags:

dataframe

r

apply

I have a dataframe like mtcars

I want to program a function that searches for all variables of mtcars that start with "c", converts them to character and saves them back to mtcars.

like image 290
user670186 Avatar asked Jan 24 '26 08:01

user670186


1 Answers

Here is one way:

f <- function(x, str = "^var") {
    want <- grep(str, names(x))
    x[, want] <- sapply(x[, want], as.character)
    x
}

[Edit: alternative version that implements the points raised by @hadley in comments.]

f <- function(x, str = "^var") {
    want <- grepl(str, names(x))
    x[, want] <- lapply(x[, want], as.character)
    x
}

The function allows you to pass through the string you want to match on, but defaults to "^var" as you requested. The "^" indicates we want to find names that start with "var", not any name that contains "var".

Example:

> bigdf <- data.frame(var1 = LETTERS[1:3], var2 = letters[1:3], var3 = 1:3, 
+                     stuff = 4:6)
> bigdf
  var1 var2 var3 stuff
1    A    a    1     4
2    B    b    2     5
3    C    c    3     6
> 
> bigdf2 <- f(bigdf)
> bigdf2
  var1 var2 var3 stuff
1    A    a    1     4
2    B    b    2     5
3    C    c    3     6
> str(bigdf2)
'data.frame':   3 obs. of  4 variables:
 $ var1 : chr  "A" "B" "C"
 $ var2 : chr  "a" "b" "c"
 $ var3 : chr  "1" "2" "3"
 $ stuff: int  4 5 6
like image 121
Gavin Simpson Avatar answered Jan 25 '26 22:01

Gavin Simpson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!