2016-09-23 29 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')) 
相关问题