可以使用dplyr::select同时选择列和更新吗?

huangapple go评论60阅读模式
英文:

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:

  1. 从数据框 a 中选择 bc 列;
  2. bc 列的类别从字符型更改为数值型。

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:

  1. select the b and c from dataframe a;
  2. change the class of b and c 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 %&lt;&gt;%    
     mutate(across(where(is.character), as.numeric))

-output

&gt; str(a)
&#39;data.frame&#39;:	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

&gt; str(a)
Classes ‘data.table’ and &#39;data.frame&#39;:	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 %&lt;&gt;%
    type.convert(as.is = TRUE)

huangapple
  • 本文由 发表于 2023年2月6日 10:58:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定