Re: [问题]常见的重复操作as.numeric用apply可否实现

楼主: celestialgod (天)   2020-02-25 11:35:40
※ 引述《empireisme (empireisme)》之铭言:
: 如题
: 在做资料分析的时候 会常遇到需要 as.factor 或是 as.numeric的操作
: 比如说我的column总共有26行
: 第一行叫a 第二行叫b 依此类推
: 如果我想要把第一到第10行都转成numeric
: 我只好笨笨的
: df$a<- as.numeric(df$a)
: df$b<- as.numeric(df$b)
: df$c<- as.numeric(df$c)
: 像这样做实在超笨的
: 有没有可能利用APPLY或是其他方式
: 让我一次性的把指定的行数 给他一个数列 例如 c(1,4,5,6,7,8)
: 就自动把指定的行数转成as.numeric 或是as.factor的结果
: 还是我必须要自己写一个函数呢QQ
我会建议用data.table,像是下面这样做
library(data.table)
DT <- data.table(CO2)
str(DT)
# Classes ‘data.table’ and 'data.frame': 84 obs. of 5 variables:
# $ Plant : Ord.factor w/ 12 levels "Qn1"<"Qn2"<"Qn3"<..: 1 1 1 1 1 1 1 2
2 2 ...
# $ Type : Factor w/ 2 levels "Quebec","Mississippi": 1 1 1 1 1 1 1 1 1 1
...
# $ Treatment: Factor w/ 2 levels "nonchilled","chilled": 1 1 1 1 1 1 1 1 1 1
...
# $ conc : num 95 175 250 350 500 675 1000 95 175 250 ...
# $ uptake : num 16 30.4 34.8 37.2 35.3 39.2 39.7 13.6 27.3 37.1 ...
# - attr(*, ".internal.selfref")=<externalptr>
to_char_cols <- c("Plant", "Type", "Treatment")
DT[ , eval(to_char_cols) := lapply(.SD, as.character), .SDcols = to_char_cols]
str(DT)
# Classes ‘data.table’ and 'data.frame': 84 obs. of 5 variables:
# $ Plant : chr "Qn1" "Qn1" "Qn1" "Qn1" ...
# $ Type : chr "Quebec" "Quebec" "Quebec" "Quebec" ...
# $ Treatment: chr "nonchilled" "nonchilled" "nonchilled" "nonchilled" ...
# $ conc : num 95 175 250 350 500 675 1000 95 175 250 ...
# $ uptake : num 16 30.4 34.8 37.2 35.3 39.2 39.7 13.6 27.3 37.1 ...
# - attr(*, ".internal.selfref")=<externalptr>
作者: empireisme (empireisme)   2020-02-27 19:46:00
作者: JuanMaestrow (多多)   2020-02-29 21:22:00
用mutate_at(c(column names),~as.numeric(.))

Links booklink

Contact Us: admin [ a t ] ucptt.com