在R

时间:2016-11-18 18:26:50

标签: r sapply

m = data.frame(c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10),
c("Lozenge","A","Lozenge","A","Lozenge","A","Lozenge","A","Lozenge","A","Lozenge","A","Lozenge","A","Lozenge","A","Lozenge","A","Lozenge","A"),
c("Lozenge","Lozenge","Lozenge","Lozenge","Lozenge","A","A","A","A","A"))

mm = data.frame(unique(m[,1]), 0, 0)
colnames(m) = c("Number","Old","New") 
colnames(mm) = c("Number","Old","New")

我目前有两个不同的数据帧,我想使用sapply来浏览m数据帧。使用mm的数字,我想看看它是否与m的数字相匹配。如果是这样,它将查看并查看“Lozenge”一词是否出现在Old列和/或New Column中。如果是这样,我想在相应的列中以+1为单位+1。我一直在玩它,但我无法绕过它。

2 个答案:

答案 0 :(得分:1)

这似乎不像apply问题,更像是操作和摘要问题。

您真的需要单独的占位符mm数据框吗?如果这样做,您可以将此链的结果设置为mm。

library(dplyr)
library(tidyr)

m %>% 
  gather(condition, value, Old, New) %>% 
  filter(value == "Lozenge") %>% 
  group_by(Number, condition) %>% 
  tally %>% 
  spread(condition, n)

  Number   New   Old
    (dbl) (dbl) (dbl)
1       1     2     1
2       2     2     1
3       3     1     1
4       4     0     1
5       5     0     1
6       6     2     1
7       7     2     1
8       8     1     1
9       9     0     1
10     10     0     1

答案 1 :(得分:1)

目前尚不清楚预期产量。 any的可能选项。假设我们要检查每个“数字”的“旧”或| any'新'值的library(data.table) setDT(m)[, Flag := as.integer(any(Old == "Lozenge")|any(New == "Lozenge")) , Number] 是否为“Lozenge”,然后执行

setDT(m)[, Flag2 := as.integer(Old == "Lozenge"|New == "Lozenge") ]

或者我们想要比较每行“Lozenge”值的“旧”和“新”

// First, find the parent widget:

stackedLayout  = panel.layout                
dockSplitPanel = stackedLayout._children[0]

// OR directly: panel.layout._children[0]


// Then set the relative sizes so the CodeMirror panel takes 60% of the width:
dockSplitPanel.setSizes([6,4])