I am a R beginner. I have two datasets like
df1 <- t(data.frame(seq(1,6,by=1),seq(6,1,by=-1)))
colnames(df1) <- c("ZZZ","YYY","CCC","DDD","XXX","KKK")
rownames(df1) <- c("a","b")
Vector1<-c("AAA", "BBB", "CCC", "DDD", "EEE", "FFF")
Vector2<-c("a", "b", "e", "f", "k", "l")
df2<-data.frame(cbind(Vector1, Vector2))
df1 is
ZZZ YYY CCC DDD XXX KKK
a 1 2 3 4 5 6
b 6 5 4 3 2 1
df2 is
Vector1 Vector2
1 AAA a
2 BBB b
3 CCC e
4 DDD f
5 EEE k
6 FFF l
I would like to replace a variable name in df1 with the value of Vector2 in df2 when the variable name in df1 is identical to the value of Vector1 in df2.
So, ideally, I would like to get something like
ZZZ YYY e f XXX KKK
a 1 2 3 4 5 6
b 6 5 4 3 2 1
I have tried to modify the codes provided in Match row names and column names to values in another data frame . But, to me changing the name of an identified variable in df1 is somewhat challenging. Any suggestion or comment will be highly appreciated.
match
and %in%
do the job. Try this:
## example 1
df1 <- t(data.frame(seq(1,6,by=1),seq(6,1,by=-1)))
colnames(df1) <- c("ZZZ","YYY","CCC","DDD","XXX","KKK")
rownames(df1) <- c("a","b")
Vector1<-c("AAA", "BBB", "CCC", "DDD", "EEE", "FFF")
Vector2<-c("a", "b", "e", "f", "k", "l")
df2<-data.frame(cbind(Vector1, Vector2))
target <- match(colnames(df1), df2$Vector1, nomatch = 0)
colnames(df1)[colnames(df1) %in% df2$Vector1] <- as.character(df2$Vector2[target])
df1 # output
ZZZ YYY e f XXX KKK
a 1 2 3 4 5 6
b 6 5 4 3 2 1
#example 2
df1 <- t(data.frame(seq(1,6,by=1),seq(6,1,by=-1)))
colnames(df1) <- c("ZZZ","YYY","CCC","DDD","XXX","KKK")
rownames(df1) <- c("a","b")
Vector1<-c("KKK", "BBB", "DDD", "XXX", "EEE", "FFF")
Vector2<-c("a", "b", "e", "f", "k", "l")
df2<-data.frame(cbind(Vector1, Vector2))
target <- match(colnames(df1), df2$Vector1, nomatch = 0)
colnames(df1)[colnames(df1) %in% df2$Vector1] <- as.character(df2$Vector2[target])
df1 # output
ZZZ YYY CCC e f a
a 1 2 3 4 5 6
b 6 5 4 3 2 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.