[英]Replacing integers in a dataframe column that's a list of integer vectors (not just single integers) with character strings in R
[英]Replacing character strings (values) in a column in R with integers in an efficient (vectorized) way
我有一個大數據框,我想用整數替換一列中的值。 此列中有超過一千個唯一字符串。 一種方法是通過for循環。 這是帶有玩具數據集的代碼:
data(mtcars)
library(stringr)
mtcars$gear = as.character(mtcars$gear)
unique_values = unique(mtcars$gear)
for (i in (1:length(unique_values))){
mtcars$gear = str_replace(string = mtcars$gear, pattern = unique_values[i], replacement = as.character(i))
}
有沒有更有效的方法?
使用dplyr
庫應該可以解決問題:
data(mtcars)
library(stringr)
library(dplyr)
mtcars$gear = as.character(mtcars$gear)
mutate(mtcars, gear = as.integer(gear))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.