简体   繁体   English

在 R 中复制数据框中的列

[英]Duplicating column in a dataframe in R

I have an example of dataframe below:我有下面的数据框示例:

Name       Class      ID
Terry      C-02       100
Jane       C-03       101
Tom        C-04       102

I want to duplicate the ID column and place it at the start of the dataframe like so:我想复制 ID 列并将其放在数据框的开头,如下所示:

ID       Name      Class      ID
100      Terry     C-02       100
101      Jane      C-03       101
102      Tom       C-04       102

I tried:我试过:

id_col <- as.data.frame(df$ID)
new_df <- cbind(id_col, df)

But I'm getting a "Large matrix" instead of a regular dataframe.但是我得到的是“大矩阵”而不是常规数据框。

Here my 50 cent.这是我的 50 美分。

df1[c(3, 1:3)]
#    ID  Name Class ID.1
# 1 100 Terry  C-02  100
# 2 101  Jane  C-03  101
# 3 102   Tom  C-04  102

cbind(df1[3], df1)
#    ID  Name Class  ID
# 1 100 Terry  C-02 100
# 2 101  Jane  C-03 101
# 3 102   Tom  C-04 102

Here are a few approaches:这里有一些方法:

Use the ID as an attribute to avoid duplicate names:使用 ID 作为attribute以避免重复名称:

structure(df, row.names= df$ID)
     Name Class  ID
100 Terry  C-02 100
101  Jane  C-03 101
102   Tom  C-04 102

Use dplyr 's select to introduce a new duplicate ID:使用dplyrselect引入新的重复 ID:

    df %>% 
 mutate(new_ID = ID) %>% 
 select(new_ID, everything())
  new_ID  Name Class  ID
1    100 Terry  C-02 100
2    101  Jane  C-03 101
3    102   Tom  C-04 102

base : base

 data.frame(ID=df$ID,df,check.names = FALSE)
   ID  Name Class  ID
1 100 Terry  C-02 100
2 101  Jane  C-03 101
3 102   Tom  C-04 102

One more (actually close to what you tried initially):再一个(实际上接近你最初尝试的):

df1 <- cbind(df[, c(3, 1:2)], ID=df$ID)
df1
   ID  Name Class  ID
1 100 Terry  C-02 100
2 101  Jane  C-03 101
3 102   Tom  C-04 102

Assuming you want exactly the result shown then the main problem is to have R not rename the second instance of the column name ID to ID.1 .假设您想要完全显示的结果,那么主要问题是让 R 不将列名ID的第二个实例重命名为ID.1 If we convert to list and back then we can use check.names = FALSE on as.data.frame like this:如果我们转换为列表并返回,那么我们可以像这样在as.data.frame上使用check.names = FALSE

as.data.frame(as.list(DF)[c(3, 1:3)], check.names = FALSE)

giving:给予:

   ID  Name Class  ID
1 100 Terry  C-02 100
2 101  Jane  C-03 101
3 102   Tom  C-04 102

Note笔记

Lines <- "Name       Class      ID
Terry      C-02       100
Jane       C-03       101
Tom        C-04       102"
DF <- read.table(text = Lines, header = TRUE, strip.white = TRUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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