根据另一列的数据创建新的变量列

时间:2014-10-14 16:26:27

标签: r

我对R很新,并且编程一般,我想知道循环列的最佳方法,所以我可以在数据框中添加一列,进一步描述我循环的观察结果

我目前有一个氨基酸列表及其在蛋白质上的位置,如下所示:

Residue Position
H   1
R   2
K   3
D   4
E   5
H   6
R   7
K   8
D   9
E   10

我喜欢看起来像这样的东西(其中H,R和K是碱性氨基酸,D和E是酸性氨基酸):

Residue Position    Properties
H   1   Basic
R   2   Basic
K   3   Basic
D   4   Acidic
E   5   Acidic
H   6   Basic
R   7   Basic
K   8   Basic
D   9   Acidic
E   10  Acidic

我真的不知道从哪里开始,而且我很难在R中找到这种情况的良好资源。

我开始试图对数据进行子集化,但后来我才意识到这不会做到这一点:

Basic
h.dat <- subset(all, all$Residue == "H")
r.dat <- subset(all, all$Residue == "R")
k.dat <- subset(all, all$Residue == "K")

Acidic
d.dat <- subset(all, all$Residue == "D")
e.dat <- subset(all, all$Residue == "E")

谢谢!

Note: 
H = Histidine (Basic amino acid)
R = Arginine (Basic)
K = Lysine (Basic)

E = Glutamic Acid (Acidic)
D = Aspartic Acid (Acidic)

3 个答案:

答案 0 :(得分:5)

您可以使用ifelse。如果df是原始数据的名称,

df$Property <- ifelse(df$Residue %in% c("H", "R", "K"), "Basic", "Acidic")
df
#    Residue Position Property
# 1        H        1    Basic
# 2        R        2    Basic
# 3        K        3    Basic
# 4        D        4   Acidic
# 5        E        5   Acidic
# 6        H        6    Basic
# 7        R        7    Basic
# 8        K        8    Basic
# 9        D        9   Acidic
# 10       E       10   Acidic

答案 1 :(得分:2)

尝试:

> df1
   Residue Position
1        H        1
2        R        2
3        K        3
4        D        4
5        E        5
6        H        6
7        R        7
8        K        8
9        D        9
10       E       10

创建参考表:

> df2
  Residue Property
1       H    Basic
2       R    Basic
3       K    Basic
4       D   Acidic
5       E   Acidic

然后合并:

> merge(df1, df2)
   Residue Position Property
1        D        9   Acidic
2        D        4   Acidic
3        E        5   Acidic
4        E       10   Acidic
5        H        1    Basic
6        H        6    Basic
7        K        8    Basic
8        K        3    Basic
9        R        7    Basic
10       R        2    Basic

答案 2 :(得分:2)

我认为您可能也想要允许非极性氨基酸:

c(rep("Basic",3),rep("Acidic",2),"Non-Polar")[   # those are the choices
        match(dat$Residue, c("H","R","K","E","D"), nomatch=6) ] #select indices

所以我添加了一个名为“Z”的第11个残基并进行了测试:

> dat$Property <- c(rep("Basic",3),rep("Acidic",2),"Non-Polar")[
                 match(dat$Residue, c("H","R","K","E","D"), nomatch=6) ]
> dat
   Residue Position  Property
1        H        1     Basic
2        R        2     Basic
3        K        3     Basic
4        D        4    Acidic
5        E        5    Acidic
6        H        6     Basic
7        R        7     Basic
8        K        8     Basic
9        D        9    Acidic
10       E       10    Acidic
11       Z       11 Non-Polar