如何在dataframe R中连接列和自定义字符串?[副本]

uemypmqf  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(76)

此问题已在此处有答案

Combine two or more columns in a dataframe into a new column with a new name(9个回答)
14天前关闭
我有一个dataframe如下:

ID  GRgroup ARgroup
MB-0000 High    Moderate
MB-0002 Moderate    High
MB-0005 High    High
MB-0006 Moderate    Low
MB-0008 High    Low
MB-0010 High    Moderate

我想连接第二和第三列。预期输出为:

ID  GRgroup ARgroup ARGR
MB-0000 High    Moderate    AR:Moderate_GR:High
MB-0002 Moderate    High    AR:High_GR:Moderate
MB-0005 High    High    AR:High_GR:High
MB-0006 Moderate    Low AR:Low_GR:Moderate
MB-0008 High    Low AR:Low_GR:High
MB-0010 High    Moderate    AR:Moderate_GR:High

我在Python中这样做了:

import pandas as pd

# Concatenate 'GRgroup' and 'ARgroup' columns with the desired format
df['ARGR'] = "AR:" + df['ARgroup'] + "_GR:" + df['GRgroup']

# Reorder the columns
df = df[['ID', 'GRgroup', 'ARgroup', 'ARGR']]

在R中该怎么做?

kmynzznz

kmynzznz1#

你可以在R中使用paste函数来连接:

#Concatenate the groups
data$ARGR <- paste("AR:", data$ARgroup, "_GR:", data$GRgroup)

#Reorder
data <- data[, c("ID", "GRgroup", "ARgroup", "ARGR")]

或者在组间没有空格的情况下得到它

data$ARGR <- paste0("AR:", data$ARgroup, "_GR:", data$GRgroup)

相关问题