Question

I have a data frame in R, say f1. I want to create another data frame f2 which has the column names(header) in f1 as f2's row names. I know there are 300 names in f1, and want to assign color "#ff0000" to the first 200 and color "#0000ff" to the last 100. How can I do this? The result should looks like,

name1   "#ff0000"
name2   "#ff0000"
...
name201 "#0000ff"
name202 "#0000ff"
...
Was it helpful?

Solution

The rbinds and cbinds in your answer are unnecessary. This is a one-liner, using data.frame.

f2 = data.frame(color = c(rep("#ff0000", 200), rep("#0000ff", 100)),
    row.names = names(f1),
    stringsAsFactors = FALSE)

OTHER TIPS

mydata<-mtcars
mydata1<-data.frame(names(mydata))
mydata1$col<-c(rep("col1",7),rep("col2",4))
rownames(mydata1)<-mydata1$names.mydata
mydata1$names.mydata.<-NULL

> mydata1
      col
mpg  col1
cyl  col1
disp col1
hp   col1
drat col1
wt   col1
qsec col1
vs   col2
am   col2
gear col2
carb col2

I have figured it out myself. First get the f1's names out, name=col.names(f1)

Then prepare the color structure, color=rbind(cbind(rep("#ff0000",200)),cbind(rep("#0000ff",100)))

Finally create the data frame, final=data.frame(color,row.names=name)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top