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

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

Is it possible to use dplyr::select to select columns and update at the same time?

问题

Sample dataset:

  1. 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:

  1. a %>% select(b, c) %>% as.numeric

The error appeared:

  1. Error in a %>% select(b, c) %>% as.numeric :
  2. 'list' object cannot be coerced to type 'double'
  3. Warning: cannot xtfrm data frames
英文:

Sample dataset:

  1. 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:

  1. a %>% select(b,c) %<>% as.numeric

The error appeared:

  1. Error in a %>% select(b, c) %<>% as.numeric :
  2. 'list' object cannot be coerced to type 'double'
  3. 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

  1. library(magrittr)
  2. a %<>%
  3. mutate(across(where(is.character), as.numeric))

-output

  1. > str(a)
  2. 'data.frame': 4 obs. of 3 variables:
  3. $ a: num 1 2 3 4
  4. $ b: num 1 2 3 4
  5. $ c: num 6 6 6 6

Or use data.table methods

  1. library(data.table)
  2. setDT(a)[, (2:3) := lapply(.SD, as.numeric), .SDcols = is.character ]

-output

  1. > str(a)
  2. Classes data.table and 'data.frame': 4 obs. of 3 variables:
  3. $ a: num 1 2 3 4
  4. $ b: num 1 2 3 4
  5. $ c: num 6 6 6 6

Or another option is to automatically convert to its type based on the value with type.convert

  1. a %<>%
  2. 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

  1. library(magrittr)
  2. a %&lt;&gt;%
  3. mutate(across(where(is.character), as.numeric))

-output

  1. &gt; str(a)
  2. &#39;data.frame&#39;: 4 obs. of 3 variables:
  3. $ a: num 1 2 3 4
  4. $ b: num 1 2 3 4
  5. $ c: num 6 6 6 6

Or use data.table methods

  1. library(data.table)
  2. setDT(a)[, (2:3) := lapply(.SD, as.numeric), .SDcols = is.character ]

-output

  1. &gt; str(a)
  2. Classes data.table and &#39;data.frame&#39;: 4 obs. of 3 variables:
  3. $ a: num 1 2 3 4
  4. $ b: num 1 2 3 4
  5. $ c: num 6 6 6 6

Or another option is to automatically convert to its type based on the value with type.convert

  1. a %&lt;&gt;%
  2. 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:

确定