简体   繁体   English

as.character,用于将一列中的值替换为另一列中的值

[英]as.character for replacing values in one column with values from another

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. 但是,“名称”字段有时为空,有时会错误地将“名称”放在“ Initials”字段中。 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. 我想创建一个Name2字段,其中在Name字段中的所有空格都用Initials字段中的相应名称填充。 Otherwise, I just want the Name2 field to be populated with values from the Name field (eg '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). 否则,我只希望用Name字段中的值填充Name2字段(例如,“ John Paul”在缩写中,但是Name为空-我希望Name2的值为“ John Paul”。“ John Brown”是在名称中,我希望它只显示在名称2中)。

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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM