简体   繁体   中英

How to assign column names from a source data frame to a target df

I have a df called "target" with column names V1:V200. I want to replace these column names with character strings that are stored in a column called V2 in a df called "nameSource".

I transposed "nameSource", using:

> wideNameSource<-as.data.frame(t(nameSource))

In the following step, I eliminated V1 from "wideNameSource" and created a new df called "JustNames". (V1 was a numeric column with values 1:200). This produced a df with a single column that contained the character strings I wanted to use as column names. These are sequenced in the same order I want to apply them to my "target" df.

> JustNames<-subset(wideNameSource[2,])

I then tried to bind the values in the "JustNames" df to the top of the "target" df using:

> targetWithColNames<-rbind(JustNames,target)

But I got a stream of warning messages like the following:

1: In `[<-.factor`(`*tmp*`, ri, value = c(0.35717, 0.82226,  ... :
  invalid factor level, NA generated

and all the (numeric) data in the targetWithColNames df showed up as NA.

What is the simplest way to get my column names from "nameSource" to "target"?

使用两个数据nameSource targetnameSource

colnames(target) <- nameSource$V1

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.

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