【发布时间】:2017-04-13 21:25:27
【问题描述】:
我正在尝试从数据框中隔离一些值 示例:
test_df0<- data.frame('col1'= c('string1', 'string2', 'string1'),
'col2' = c('value1', 'value2', 'value3'),
'col3' = c('string3', 'string4', 'string3'))
我想获得一个新的数据框,其中只有来自 col1 的唯一字符串,以及来自 col3 的相关字符串(对于具有相同 col1 的行,这将是相同的。 这是我写的循环,但我一定犯了一些直截了当的错误:
test_df1<- as.data.frame(matrix(ncol= 2, nrow=0))
colnames(test_df1)<- c('col1', 'col3')
for (i in unique(test_df0$col1)){
first_matching_row<- match(x = i, table = test_df0$col1)
temp_df<-
data.frame('col1'= i,
'col3'= test_df0[first_matching_row, 'col3'])
rbind(test_df1, temp_df)}
生成的 test_df1 虽然是空的。无法发现循环的错误,如果有任何建议,我将不胜感激。
编辑:for 循环正在工作,如果它的最后一行是 print(temp_df) 而不是 rbind 命令,我会得到正确的结果。我不确定为什么 rbind 不工作
【问题讨论】:
-
test_df0[!duplicated(test_df0[["col1"]]), c("col1", "col3")]是否符合您的要求?如果是这样,我可以把它写成答案并解释它在做什么。 -
像魅力一样工作!你介意解释一下为什么循环不起作用吗?谢谢
-
@Istrel 这行不通,因为
col2的值不一样。你必须这样做test_df1 <- unique(test_df0[c("col1", "col3")])。