as.character用一个列替换另一个值中的值

时间:2022-09-29 07:58:03

I have a dataframe with a series of Initials and Names. However, occasionally Names were erroneously sitting in the Initials field, with the Name field being blank. It looked like this:

我有一个包含一系列姓名缩写和名称的数据框。但是,偶尔名称错误地位于“首字母”字段中,“名称”字段为空。它看起来像这样:

Initials <- c('JB', 'MJ', 'SF', 'Obi Wan Kanobi', 'Luke Skywalker', 'LO', 'Darth 
              Vader', 'JS', 'MM', 'John Paul')
Name <- c('John Brown', 'Mike Jones', 'Sally Fields', '', '', 'Leia Organa', '', 
           'Joey Scarface', 'Marilyn Monroe', '')
test <- data.frame(Initials, Name)

I want to create a Name2 field, where any blanks in the Name field are populated with the corresponding name in the Initials field. Otherwise, I just want the Name2 field to be populated with values from the Name field (e.g. 'John Paul' is in Initials, but Name is blank -- I want Name2 to have the value 'John Paul'. 'John Brown' is in Name, and I want it to just show up in Name2).

我想创建一个Name2字段,其中Name字段中的任何空格都填充了Initials字段中的相应名称。否则,我只想在Name2字段中填充Name字段中的值(例如'John Paul'在Initials中,但Name是空白的 - 我希望Name2的值为'John Paul'。'John Brown'是在Name中,我希望它只显示在Name2中。

I tried the following code, but it simply spit out a vector of numbers for Name2:

我尝试了下面的代码,但它只是为Name2吐出一个数字向量:

test$Name2 <- ifelse(test$Name == '', test$Initials, test$Name)

1 个解决方案

#1


1  

This was a simple matter of correctly defining the field types. In this case, all my input fields were recognized as factors rather than characters. So the successful code looked like this:

这是正确定义字段类型的简单问题。在这种情况下,我的所有输入字段都被识别为因子而不是字符。所以成功的代码看起来像这样:

test$Name2 <- ifelse(test$Name == '', as.character(test$Initials), as.character(test$Name))

#1


1  

This was a simple matter of correctly defining the field types. In this case, all my input fields were recognized as factors rather than characters. So the successful code looked like this:

这是正确定义字段类型的简单问题。在这种情况下,我的所有输入字段都被识别为因子而不是字符。所以成功的代码看起来像这样:

test$Name2 <- ifelse(test$Name == '', as.character(test$Initials), as.character(test$Name))