簡體   English   中英

如何使用分隔符將數據框中的兩個新的數字列連接在一起?

[英]How to join two new numeric columns in a dataframe using a separator?

我有數據框df:

start   end
836 845
3341    3350
4647    4661
4932    4942
10088   10098
13679   13690
16888   16954
20202   20225

現在,我需要第三列“ JoinedCol”作為

836:845
3341:3350
4647:4661
4932:4942
10088:10098
...
...

我不想使用paste(),因為它正在生成具有char-type或factor的列。 我想在R中使用新列“ JoinedCol”來獲取數據

836, 837,838,...844,845,3341,3342........ ..... 10098

據我所知,R中不能包含此類數據。如果將':'符號連接到任何數字,則新字符串將始終是一個因子,一個字符或一個矩陣。

要從該特定列中檢索數據,您必須指定所需的部分,用substring() 否則,您必須將兩個數字放在不同的列中,就像原始數據框一樣。


不過,您仍然可以使用新的JoinedCol獲取數據:

>DF$JoinedCol=paste(DF$start,DF$end, sep=":") #Create the new column as you say

DF
  start   end  JoinedCol
1   836 10088  836:10088
2   845 10098  845:10098
3  3341 13679 3341:13679
4  3350 13690 3350:13690
5  4647 16888 4647:16888
6  4661 16954 4661:16954
7  4932 20202 4932:20202
8  4942 20225 4942:20225

>substring(DF$JoinedCol,1,((regexpr(":", DF$JoinedCol))-1)) #To get first set of numbers (before the ':')

[1] "836"  "845"  "3341" "3350" "4647" "4661" "4932" "4942"

>substring(DF$JoinedCol,(regexpr(":", DF$JoinedCol))+1,nchar(DF$JoinedCol)) #To get second set of numbers (after the ':')

[1] "10088" "10098" "13679" "13690" "16888" "16954" "20202" "20225"

基於

我想在R中使用新列“ JoinedCol”來進一步獲取836、837,838,... 844,845,3341,3342之類的數據........... 10098

您實際上想要這樣:

DF <- read.table(text = "start   end
                      836 845
                 3341    3350
                 4647    4661
                 4932    4942
                 10088   10098
                 13679   13690
                 16888   16954
                 20202   20225", header = TRUE)

#create the sequences
DF$sequences <- Map(`:`, DF$start, DF$end)

#access the first sequence
DF$sequences[[1]]
#[1] 836 837 838 839 840 841 842 843 844 845

您不應該按照問題的建議將命令創建為文本,然后將其解析。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM