문제

I have a data frame like the following

c1 c2
1 2
1 3
2 4
2 5
2 2
3 1
3 2
...

I want to get unique c1 values, where c2 can be chosen with equal probability if there are multiple rows with the same c1 value. For example, the final result can be:

c1 c2
1 2
2 2
3 2
...

"A random choice of c2 for each possible value of c1" is what I want.

도움이 되었습니까?

해결책

Here's a simple way to do it. Let's say your dataframe is called df.

x = unique(df$c1);
y = sapply(x, function(arg)sample(df$c2[df$c1 == arg], 1));
new_df = data.frame(c1 = x, c2 = y);

다른 팁

Here's an easy way to sample a value of c2 for each unique value of c1:

aggregate(c2 ~ c1, dat, sample, 1) # dat is the name of you data frame

  c1 c2
1  1  2
2  2  4
3  3  1
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top