简体   繁体   English

以有效(矢量化)方式用整数替换R中的列中的字符串(值)

[英]Replacing character strings (values) in a column in R with integers in an efficient (vectorized) way

I have a big dataframe and I want to replace the values in a column which are character strings with integers. 我有一个大数据框,我想用整数替换一列中的值。 There are more than one thousand unique strings in this column. 此列中有超过一千个唯一字符串。 One way is through a for loop. 一种方法是通过for循环。 Here is the code with a toy dataset: 这是带有玩具数据集的代码:

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))

}

Is there a more efficient way? 有没有更有效的方法?

Using the dplyr library should do the trick: 使用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.

相关问题 用R中的字符串替换数据帧列中的整数,该数据帧列是整数向量列表(不仅仅是单个整数) - Replacing integers in a dataframe column that's a list of integer vectors (not just single integers) with character strings in R 使用字符串列表 R 替换所有列值的有效方法 - Efficient way to replace all column values using list of strings R 替换矩阵 (R) 中值的有效方法 - Efficient way of replacing values in matrix (R) R:替换数据帧中字符串的有效方法(表) - R: Efficient way for replacing strings in a data frame(table) 需要帮助将列中的字符串替换为 R 中的值 - Need help replacing character strings found in a column with a value in R R:基于字符串替换列值的有效方法(可能使用 case_when 或某种其他形式的 mutate)? - R: Efficient way to replace column values based on strings (maybe with case_when or some other form of mutate)? R中的数据操作:用字符串系统替换列中的值 - Data Manipulation in R: Systematically replacing values in a column with strings 根据 R 中其他字符串仅替换列中的 NA 值 - Replacing only NA values in a column based on strings in others in R 如果R中包含字符串或字符,则替换列的行值 - Replacing Column row values if it contains a string or character in R 替换R中的列值 - Replacing column values in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM