2016-09-23 22 views
0

如果我不需要,我不想循環!我想遍歷列表中的每個值,我想在數據框中查找該值,並從另一列(如vlookup)中提取數據。我盡我所能在下面的代碼中解釋更多細節。R - 使用List值查找並返回datafarme中的值

# Create First dataframe 
df = data.frame(Letter=c("a","b","c"), 
       Food=c("Apple","Bannana","Carrot")) 

# Create Second dataframe 
df1 = data.frame(Testing=c("ab","abc","c")) 

# Create Function    
SplitAndCalc <- function(i,dat){ 
    # Split into characters 
    EachCharacter <- strsplit(as.character(dat$Testing), "") 

    # Iterate through Each Character, look up the matching Letter in df, pull back Food from df 

    # In the end df1 will looks something like Testing=c("ab","abc","c"), Food=c("Apple","AppleBannanaCarrot","Carrot") 

    return(Food) 
} 

library("parallel") 
library("snow") 

# Detect the number of CPU cores on local workstation 
num.cores <- detectCores() 

# Create cluster on local host 
cl <- makeCluster(num.cores, type="SOCK") 

# Get count of rows in dataframe 
row.cnt = nrow(df1) 

# Call function in parallel 
system.time(Weight <- parLapply(cl, c(1:row.cnt), SplitAndCalc, dat=df1)) 

# Create new column in dataframe to store results from function 
df1$Food <- NA 

# Unlist the Weight to fill out dataframe 
df1$Food <- as.numeric(unlist(Weight)) 

謝謝!

+0

所以「AB」將與「A」和「B」相匹配的食物,不論順序,對於其他組合類似? – Joy

+0

我想分割出每個值,所以我不想看「ab」,我想看看「a」並帶回一個值,然後看看「b」並帶回一個值。所以「ab」會帶回「AppleBannana」,「ba」會帶回「Bannana Apple」。希望有所幫助。 – JRDew

+0

即使您沒有完整的答案,請發表評論,也許它會讓我(或其他人)走上正確的道路。這對我來說很重要,我被困住了。再次感謝! – JRDew

回答

0

我想我找到的東西,會爲我工作,張貼櫃面它可以幫助別人......

# Create First dataframe 
df = data.frame(Letter=c("a","b","c"), 
       Food=c("Apple","Bannana","Carrot")) 

# Create Second dataframe 
df1 = data.frame(ID=c(1,2,3,4,5), 
    Testing=c("ab","abc","a","cc","abcabcabc")) 

# Split into individual characters 
EachCharacter <- strsplit(as.character(df1$Testing), "") 

# Set the names of list values to df1$ID so we can merge back together later 
temp <- setNames(EachCharacter,df1$ID) 

# Unlist temp list and rep ID for each letter 
out.dat <- data.frame(ID = rep(names(temp), sapply(temp, length)), 
         Letter = unlist(temp)) 

# Merge Individual letter weight 
PullInLetterFood <- (merge(df, out.dat, by = 'Letter')) 
相關問題