如何更改r中vector中存储的列的列类型

时间:2017-10-03 09:43:23

标签: r

我在r

中有以下数据框
  qty_1    qty_2    qty_3     make_1     make_2    make_3    qty_4
    1        22       33       21          5         55        6
    2        33       92       83          76        65        23

我的矢量如下

 qty_vec <- c("qty_1","qty_2","qty_3")

我想将与qty_vec匹配的列的数据类型更改为字符

我在r中关注,但它不起作用

final_df[,names(final_df)[names(final_df) %in% qty_vec]] <- lapply(final_df[,names(final_df)[names(final_df) %in% qty_vec]], function(x) 
type.convert(as.character(x)))

1 个答案:

答案 0 :(得分:0)

根据Sotos' comment above,另请参阅this SO question

df <- structure(list(qty_1 = 1:2, qty_2 = c(22L, 33L), qty_3 = c(33L, 
92L), make_1 = c(21L, 83L), make_2 = c(5L, 76L), make_3 = c(55L, 
65L), qty_4 = c(6L, 23L)), .Names = c("qty_1", "qty_2", "qty_3", 
"make_1", "make_2", "make_3", "qty_4"), class = "data.frame", row.names = c(NA, 
-2L))
str(df)
#> 'data.frame':    2 obs. of  7 variables:
#>  $ qty_1 : int  1 2
#>  $ qty_2 : int  22 33
#>  $ qty_3 : int  33 92
#>  $ make_1: int  21 83
#>  $ make_2: int  5 76
#>  $ make_3: int  55 65
#>  $ qty_4 : int  6 23
qty_vec <- c("qty_1","qty_2","qty_3")
df[qty_vec] <- lapply(df[qty_vec], as.character)
str(df)
#> 'data.frame':    2 obs. of  7 variables:
#>  $ qty_1 : chr  "1" "2"
#>  $ qty_2 : chr  "22" "33"
#>  $ qty_3 : chr  "33" "92"
#>  $ make_1: int  21 83
#>  $ make_2: int  5 76
#>  $ make_3: int  55 65
#>  $ qty_4 : int  6 23