首页 > 解决方案 > R: Creating a new column with desired alphabets

问题描述

I am a beginner in R, so I am sorry if my question is too basic, but I would really appreciate some help in this.

  mydata <-
structure(list(Col1 = c(17, 28, 80, 63, 20, 
10), Col2 = c(18, 27, 89, 62, 24, 
11), Col3 = c(25, 40, 80, 65, 23, 
11), Col4 = c(27, 29, 100, 72, 34, 
6)), class = "data.frame", 
row.names = c("row1", "row2", "row3", "row4", "row5", 
"row6"))

I would like to add a new column 'X'. For 'X', I would like to assign A for Row 1-2, B for row 3-4, C for row 5 and D for row 6.

The code I tried is..

mydata$X[mydata[c(1:2),]]<-A
mydata$X[mydata[c(3:4),]]<-B
mydata$X[mydata[c(5),]]<-C
mydata$X[mydata[c(6),]]<-D

I tried putting "" e.g. "A" when I am assigning letters, but couldn't get it to work.

I got error message:

invalid subscript type 'list'

So, I tried unlisting my data, but still did not work.

Can anybody help please?

标签: rlistdataframedata-manipulation

解决方案


r2evans 已完全回答了原始问题 这是一个新的且不清楚的分类问题:“我想根据我的序列的开头将它们分为四个不同的组(A、T、C、G)。这似乎也得到了回答r2evans:mydata$X[1:2] <- "A" 可扩展为:mydata$X <- c(rep("A",2), rep("B",2),rep("C",1),rep("D",1)) Ronak 最近的回答当然更有说服力!


推荐阅读