[英]How would I separate a column of numbers based on numerical values in r?
trying to find the right code to use to try and separate the column of tests into two different columns named Test1 and Test2.试图找到正确的代码来尝试将测试列分成两个不同的名为 Test1 和 Test2 的列。 I tried using the separate function like so but always get two columns but 'test2' column is just na's.
我尝试使用单独的函数,但总是得到两列,但“test2”列只是 na 的。
Tests
1
1
2
2
1
2
1
2
1
code used
separate(Tests, c('test1', 'test2'))
i want it to look like this.我希望它看起来像这样。 Not sure if i have the wrong function of if i have to add something else into the function to get the column to separate how i want it to.
不知道我是否有错误的功能,如果我必须在函数中添加其他东西才能让列分开我想要的方式。 Any advice would help :) thank you!
任何建议都会有所帮助:)谢谢!
test1 test2
1 2
1 2
1 2
1 2
1 2
I am supposing that your Tests is a simple vector (guess they are tecnically called atomic vectors but I could be wrong):我假设您的测试是一个简单的向量(猜测它们在技术上被称为原子向量,但我可能是错的):
Tests <- c(1,1,2,2,1,2,1,2,1)
You could just filter according to the condition and bind the result into a new data.frame (if Tests is a data.frame with on column called "Tests" just put a "," before each "]":您可以根据条件进行过滤并将结果绑定到一个新的 data.frame 中(如果 Tests 是一个 data.frame,其列名为“Tests”,只需在每个“]”之前放一个“,”:
as.data.frame(cbind(Test1 = Tests[Tests == 1], Test2 = Tests[Tests == 2]))
But as you will see R gives you a warning, because there are more 1s than 2s and here comes a very important thing to notice: R will recycle the shorter vector to fill up the data.frame Because in a data.frame all columns have to be of the same length!但是正如您将看到的,R 会给您一个警告,因为 1s 比 2s 多,这里有一件非常重要的事情要注意:R 将回收较短的向量来填充 data.frame 因为在 data.frame 中所有列都有长度相同!
So what you are looking to do is dangerous as you most probably can not be sure that everything will have the same length.因此,您要做的事情很危险,因为您很可能无法确定所有内容都具有相同的长度。 Possibly the recycling is not desired behaviour so be aware of that.
可能回收不是期望的行为,所以要注意这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.