如何获取完全相同的行(除了最后的数字)并将其附加到另一行?我尝试使用
df<-data.frame(
Participant=c("bob1","bill1","bob2","bill2"),
No_Photos=c(1,4,5,6)
)
library(tidyr)
library(dplyr)
df%>% Participant = gsub("[0-9]", "", Participant) %>% group_by(Participant) %>% rbind(Participant[1],Participant[2])
目标:
Participant No_Photos Participant No_Photos
Bill1 4 Bill2 6
Bob1 1 Bob2 5
答案 0 :(得分:1)
以下是使用dcast
的选项。我们从'Participant'中提取非数字字符以创建'ind',然后使用它来获取序列('N'),然后使用library(data.table)
setDT(df)[, ind := sub('\\D+', '', Participant)][, N:= 1:.N, ind]
dcast(df, N~ind, value.var=c('Participant', 'No_Photos'))
# N Participant_1 Participant_2 No_Photos_1 No_Photos_2
#1: 1 bob1 bob2 1 5
#2: 2 bill1 bill2 4 6
转换为宽格式。
public void add(Integer a)
{
// If fewer than 3 elements in the list, add and we're done.
if (m.size() < 3)
{
m.add(a);
return;
}
// If there's 3 elements, find the maximum.
int max = Integer.MIN_VALUE;
int index = -1;
for (int i=0; i<3; i++) {
int v = m.get(i);
if (v > max) {
max = v;
index = i;
}
}
// If a is less than the max, we need to add it and remove the existing max.
if (a < max) {
m.remove(index);
m.add(a);
}
}
答案 1 :(得分:0)
我想你可能会想要这样的东西:
library(tidyr)
library(dplyr)
library(rex)
df %>%
extract(Participant,
c("name", "number"),
rex(capture(letters), capture(numbers)),
remove = FALSE) %>%
gather(variable, value,
No_Photos, Participant) %>%
unite(new_variable,
variable, number) %>%
spread(new_variable, value)