2017-02-23 7 views
-1

にデータフレーム内のリストを変換します私は、次のデータフレームを持つベクトル

Offer ID Item ID 
162840 56A340942123, 902G569800234 
162841 96A3403718213, 872M569814535, M235481980234, 890TG56248191 
162842 H79

オファーIDは文字ベクトルであり、アイテムIDがリストです。ここでは、アイテムIDには3つの要素があり、各行に1つずつあります。

アイテムIDをリストからベクターに変換して、同じ行内の各アイテムIDを個別に参照できるかどうかを確認します。

私はRに比較的新しいです。私はunlist、do.call、および貼り付けを試してみました。それらはすべて私のデータフレームの寸法を乱すものです。

注:サブリストに分割したくありません。

ETA:dputの出力 -

structure(list(Col1 = c(162840L, 162841L, 162842L, 162843L, 162845L, 
162847L, 162849L), Col2 = structure(list(`1` = c("137089", "668552", 
"346129"), `4` = c("442054", "479934", "58316"), `7` = c("149298", 
"533977", "598069"), `10` = c("898134", "614982", "581007", "570515" 
), `14` = c("93015", "252103", "639482", "226594", "64429"), 
    `19` = c("328971", "604454", "603078"), `22` = "93774"), .Names = c("1", 
"4", "7", "10", "14", "19", "22"))), .Names = c("Col1", "Col2" 
), row.names = c(NA, -7L), class = "data.frame") 

予想される出力:

Offer ID Item ID1 Item ID2 Item ID3 Item ID4 
168240  137089  668552  346129 
162841  442054  479934  58316 
162842  149298  533977  598069 
162843  898134  614982  581007  570515 
+0

使用 'csplitコマンド(DF1、 "項目ID" 、 "、"、 "long") ' – akrun

+1

@akrun 'splitstackshape :: cSplit'を参照していますか?実際には、非標準関数のソースを修飾する必要があります。 – r2evans

+0

あなたの予想される出力はどれくらいですか? (ところで、あなたの 'dput'edデータがあなたの最初のdata.frameと一致しません。他の何かがここにありますか?) – r2evans

答えて

0
# get length of the largest vector 
max_cols <- max(unlist(lapply(df1$Col2, length))) 

# fill with NA to make it equal length 
a1 <- lapply(df1$Col2, function(x) c(x, rep(NA, (max_cols - length(x))))) 

# combine column 1 with transformed data 
df1 <- do.call('cbind', list(df1$Col1, do.call('rbind', a1))) 

# apply column names 
colnames(df1) <- paste("Col", 1: (max_cols+1), sep = '') 

# convert to numeric data type 
df1 <- data.frame(apply(df1, 2, as.numeric)) 

df1 
#  Col1 Col2 Col3 Col4 Col5 Col6 
# 1 162840 137089 668552 346129  NA NA 
# 2 162841 442054 479934 58316  NA NA 
# 3 162842 149298 533977 598069  NA NA 
# 4 162843 898134 614982 581007 570515 NA 
# 5 162845 93015 252103 639482 226594 64429 
# 6 162847 328971 604454 603078  NA NA 
# 7 162849 93774  NA  NA  NA NA 

データ:

df1 <- structure(list(Col1 = c(162840L, 162841L, 162842L, 162843L, 162845L, 162847L, 162849L), 
         Col2 = structure(list(`1` = c("137089", "668552", "346129"), 
              `4` = c("442054", "479934", "58316"), 
              `7` = c("149298", "533977", "598069"), 
              `10` = c("898134", "614982", "581007", "570515"), 
              `14` = c("93015", "252103", "639482", "226594", "64429"), 
              `19` = c("328971", "604454", "603078"), 
              `22` = "93774"), 
             .Names = c("1", "4", "7", "10", "14", "19", "22"))), 
       .Names = c("Col1", "Col2"), 
       row.names = c(NA, -7L), 
       class = "data.frame") 
+0

ありがとう!これは私のために働く。 – user1834217

関連する問題