英文:
Is it possible to use dplyr::select to select columns and update at the same time?
问题
Sample dataset:
a = data.frame(a=c(1,2,3,4), b = c('1', '2', '3', '4'), c = c('6', '6', '6', '6'))
What I want to do is:
- 从数据框
a
中选择b
和c
列; - 将
b
和c
列的类别从字符型更改为数值型。
The code that I tried:
a %>% select(b, c) %>% as.numeric
The error appeared:
Error in a %>% select(b, c) %>% as.numeric :
'list' object cannot be coerced to type 'double'
Warning: cannot xtfrm data frames
英文:
Sample dataset:
a = data.frame(a=c(1,2,3,4),b = c('1','2','3','4'),c=c('6','6','6','6'))
What I want to do is:
- select the
b
andc
from dataframea
; - change the class of
b
andc
from character to numeric
The code that I tried:
a %>% select(b,c) %<>% as.numeric
The error appeared:
Error in a %>% select(b, c) %<>% as.numeric :
'list' object cannot be coerced to type 'double'
Warning: cannot xtfrm data frames
答案1
得分: 2
We may use mutate
with across
as as.numeric
expects a vector
as input and not a data.frame or list
library(magrittr)
a %<>%
mutate(across(where(is.character), as.numeric))
-output
> str(a)
'data.frame': 4 obs. of 3 variables:
$ a: num 1 2 3 4
$ b: num 1 2 3 4
$ c: num 6 6 6 6
Or use data.table
methods
library(data.table)
setDT(a)[, (2:3) := lapply(.SD, as.numeric), .SDcols = is.character ]
-output
> str(a)
Classes ‘data.table’ and 'data.frame': 4 obs. of 3 variables:
$ a: num 1 2 3 4
$ b: num 1 2 3 4
$ c: num 6 6 6 6
Or another option is to automatically convert to its type based on the value with type.convert
a %<>%
type.convert(as.is = TRUE)
英文:
We may use mutate
with across
as as.numeric
expects a vector
as input and not a data.frame or list
library(magrittr)
a %<>%
mutate(across(where(is.character), as.numeric))
-output
> str(a)
'data.frame': 4 obs. of 3 variables:
$ a: num 1 2 3 4
$ b: num 1 2 3 4
$ c: num 6 6 6 6
Or use data.table
methods
library(data.table)
setDT(a)[, (2:3) := lapply(.SD, as.numeric), .SDcols = is.character ]
-output
> str(a)
Classes ‘data.table’ and 'data.frame': 4 obs. of 3 variables:
$ a: num 1 2 3 4
$ b: num 1 2 3 4
$ c: num 6 6 6 6
Or another option is to automatically convert to its type based on the value with type.convert
a %<>%
type.convert(as.is = TRUE)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论