更改字符向量的所选元素 [英] Change selected elements of character vector
本文介绍了更改字符向量的所选元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
data1< -data。是否有更短版本的原始重命名数据框的某些列? frame(a= 1:3,b= 1:3,c= 1:3)
data1Names< -names(data1)
data1Names [data1Names == a]< - hello
data1Names [data1Names ==c]< - world
名称(data1)< -data1Names
解决方案
使用 match
替换所选元素在使用名称时遵守订单
名称(data1)[match(c(a,c),names(data1))]< - c(hello,world)
#hello b world
# 1 1 1
#2 2 2 2
#3 3 3 3
交换所需的重命名顺序...
names(data1)[match(c(c,a) ,name(data1))]< - c(hello,world)
#world b hello
#1 1 1 1
#2 2 2 2
#3 3 3 3
Is there a shorter version for the folowing principle to rename certain columns of a data frame?
data1<-data.frame("a"=1:3,"b"=1:3,"c"=1:3)
data1Names<-names(data1)
data1Names[data1Names=="a"]<-"hello"
data1Names[data1Names=="c"]<-"world"
names(data1)<-data1Names
解决方案
Use match
to replace selected elements and to respect the order when using names<-
...
names(data1)[ match( c("a", "c") , names(data1) ) ] <- c("hello", "world")
# hello b world
#1 1 1 1
#2 2 2 2
#3 3 3 3
Swapping the desired order of renaming...
names(data1)[ match( c("c", "a") , names(data1) ) ] <- c("hello", "world")
# world b hello
#1 1 1 1
#2 2 2 2
#3 3 3 3
这篇关于更改字符向量的所选元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文