简体   繁体   中英

making R functions

I am trying to make function to change column types.

sample

df = data.table(commission = as.character(c("100 EUR", "200 EUR", "300 EUR")))
df$commission <- as.character(df$commission)

str(df)
 #Classes ‘data.table’ and 'data.frame':    3 obs. of  1 variable:
 #$ commission: chr  "100 EUR" "200 EUR" "300 EUR"
 #- attr(*, ".internal.selfref")=<externalptr> 

function

colconv <- function(data,colname){
        data$colname <- gsub(data$colname, pattern = " EUR", replacement = "", fixed = T)
        data$colname <- as.numeric(data$colname)
        data
}

And I get...

colconv(df, commission)

#Classes ‘data.table’ and 'data.frame': 3 obs. of  1 variable:
#$ commission: chr  "100 EUR" "200 EUR" "300 EUR"
#- attr(*, ".internal.selfref")=<externalptr> 

it processes through R but it changes nothing.

Can anyone suggest how to make it work? or any other solution that is smarter?

You're probably better off just writing your function to act on a vector, and then call it to assign your new variable

colconv <- function(x){ as.numeric(gsub(x, pattern = " EUR", replacement = "", fixed = T)) } 

...for instance. Then:

df[, commission := colconv(commission)] 

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