将R中的数据帧变换为单独列的简单方法 [英] Easy way to transform data frame in R - one variable values as separate columns

查看:208
本文介绍了将R中的数据帧变换为单独列的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有什么(显然我提供了我目前数据的一小部分):

What I have (obviously I'm presenting a very small fraction of my current data):

my_df <- structure(list(X = structure(c(48.75, 49.25), .Dim = 2L), Y = structure(c(17.25, 17.25), .Dim = 2L), Time = structure(c(14625, 14626), .Dim = 2L, class = "Date"), spei = c(-0.460236400365829, -0.625695407390594)), .Names = c("X", "Y", "Time", "spei"), row.names = 1:2, class = "data.frame")

我需要什么:

new_df <- structure(list(X = structure(c(48.75, 49.25), .Dim = 2L), Y = structure(c(17.25, 17.25), .Dim = 2L), "2010-01-16" = c(-0.460236400365829, NaN), "2010-01-17" = c(NaN, -0.625695407390594)), .Names = c("X", "Y", "2010-01-16", "2010-01-17"), row.names = 1:2, class = "data.frame")

最简单的方法是什么?
我想过要写一个for循环,但是我猜应用/ sapply可能有帮助吗?

What is the easiest way of doing this? I thought about writing a for loop, but I guess that apply/sapply might help on this?

推荐答案

您可以使用库 tidyr 及其传播这样的功能:

You can use library tidyr and its spread function like this:

library(tidyr)
spread(my_df, Time, spei)
      X     Y 2010-01-16 2010-01-17
1 48.75 17.25 -0.4602364         NA
2 49.25 17.25         NA -0.6256954

这篇关于将R中的数据帧变换为单独列的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆