简体   繁体   中英

Change value of each row of dataframe column with a function

I have a function which appends a "0" to the from of a value if that value is only 1 char in length:

myFormat <- function(v) {
  if(nchar(v) == 1){
    paste0("0",v)
  }
  else
    as.character(v)
}

I have a dataframe DF with a column named A of type character that looks like:

A
3
12
5
10
1
...

After running myFormat() , column A should look like:

A
03
12
05
01
...

I tried: DF$A <- lapply(DF$A, weekFormat(DF$A)) but am getting errors.

I also tried: mutate(DF, newCol = myFormat(A)) but get error there saying only first element will be used.

Also tried: cbind(DF, lapply(DF$A, wmyFormat) but this adds many new columns.

Whats going wrong? Is there a better way to do this?

This could be easily done using sprintf . Using @nrussell's data

DF$A <- sprintf("%02d", DF$A)
DF$A
#[1] "03" "12" "05" "10" "01"

You can just use sapply instead of lapply :

DF <- data.frame(A=c(3,12,5,10,1))
> DF
   A
1  3
2 12
3  5
4 10
5  1
##
DF$A <- sapply(DF$A, myFormat)
> DF
   A
1 03
2 12
3 05
4 10
5 01

There's no need to make a function to do this. Just use sprintf.

DF$A<-sprintf("%02d",DF$A)

You get that error because if is not vectorized, and uses only the first element. sprintf is the best answer, IMO. But to fix your error, try ifelse in your function.

ifelse(nchar(x) == 1, paste0("0", x), x)
# [1] "03" "12" "05" "10" "01"

You can also use a vector subset in your function. That way it can be used nicely with lapply

myFormat <- function(v) {
    w <- which(nchar(v) == 1)
    v[w] <- paste0("0", v[w])   
    v
}
lapply(DF, myFormat)
# $A
# [1] "03" "12" "05" "10" "01"

But sprintf is definitely better for what you are doing.

I'm assuming that weekFormat is supposed to be myFormat of vice versa. This is what you want

DF$A <- unlist(lapply(DF$A, myFormat))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM