合并数据帧中的两列,特定情况下使用R。

huangapple go评论70阅读模式
英文:

Merge two colum of a data frame with particulars cases R

问题

You can achieve the desired result by concatenating the values from the "MANUAL.ID" and "AUTO.ID" columns into a new "species" column in your data frame. Here's an example of how to do it in Python using the pandas library:

import pandas as pd

# Create your DataFrame
data = {'MANUAL.ID': ['Barbar', 'Barbar', 'Barbar', 'Barbar', 'Pippip', ''],
        'AUTO.ID': ['Barbar', '', 'Pippip', 'Pippip,Hypsav', 'Barbar', 'Barbar,Pippip']}
df = pd.DataFrame(data)

# Concatenate the values from both columns into a new 'species' column
df['species'] = df['MANUAL.ID'] + ',' + df['AUTO.ID']

# Display the resulting DataFrame
print(df[['species']])

This code will create a new "species" column in your DataFrame that contains the merged values from "MANUAL.ID" and "AUTO.ID," separated by a comma.

英文:

I have a data frame which looks like that :

MANUAL.ID AUTO.ID
Barbar Barbar
Barbar
Barbar Pippip
Barbar Pippip,Hypsav
Pippip Barbar
Barbar,Pippip

Basically I whould merge the both columns in a single called species and obtain this kind of result :

species
Barbar,Barbar
Barbar
Barbar,Pippip
Barbar,Pippip,Hypsav
Pippip,Barbar
Barbar,Pippip

What can I do to get the result ?

答案1

得分: 1

An approach using paste with apply

data.frame(species = apply(df, 1, function(x) 
  ifelse(any(x == ""), paste(x, collapse=""), paste(x, collapse=","))))
               species
1        Barbar,Barbar
2               Barbar
3        Barbar,Pippip
4 Barbar,Pippip,Hypsav
5        Pippip,Barbar
6        Barbar,Pippip

Data

df <- structure(list(MANUAL.ID = c("Barbar", "Barbar", "Barbar", "Barbar", 
"Pippip", ""), AUTO.ID = c("Barbar", "", "Pippip", "Pippip,Hypsav", 
"Barbar", "Barbar,Pippip")), row.names = c(NA, -6L), class = "data.frame")

(Note: I've translated the code part as requested.)

英文:

An approach using paste with apply

data.frame(species = apply(df, 1, function(x) 
  ifelse(any(x == &quot;&quot;), paste(x, collapse=&quot;&quot;), paste(x, collapse=&quot;,&quot;))))
               species
1        Barbar,Barbar
2               Barbar
3        Barbar,Pippip
4 Barbar,Pippip,Hypsav
5        Pippip,Barbar
6        Barbar,Pippip

Data

df &lt;- structure(list(MANUAL.ID = c(&quot;Barbar&quot;, &quot;Barbar&quot;, &quot;Barbar&quot;, &quot;Barbar&quot;, 
&quot;Pippip&quot;, &quot;&quot;), AUTO.ID = c(&quot;Barbar&quot;, &quot;&quot;, &quot;Pippip&quot;, &quot;Pippip,Hypsav&quot;, 
&quot;Barbar&quot;, &quot;Barbar,Pippip&quot;)), row.names = c(NA, -6L), class = &quot;data.frame&quot;)

huangapple
  • 本文由 发表于 2023年4月17日 18:59:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034418.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定