Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 用宏转换数据_R_Data Manipulation - Fatal编程技术网

R 用宏转换数据

R 用宏转换数据,r,data-manipulation,R,Data Manipulation,我希望使用循环而不是典型的转置函数来转置数据,这样就不必将数据与未使用的变量合并 我掌握的数据如下: df1 <- data.frame(ID=c(1:4), Amount=c(100, 150, 75, 50), Month=c("Jan", "Feb", "Mar", "Apr")) 我希望最终结果如下: ID Amount Jan Feb Mar Apr 1 100 1 0 0 0 2 150 0 1 0 0 3 75

我希望使用循环而不是典型的转置函数来转置数据,这样就不必将数据与未使用的变量合并

我掌握的数据如下:

df1 <- data.frame(ID=c(1:4), Amount=c(100, 150, 75, 50), 
    Month=c("Jan", "Feb", "Mar", "Apr"))
我希望最终结果如下:

ID Amount Jan Feb Mar Apr
1    100   1   0   0   0
2    150   0   1   0   0
3     75   0   0   1   0
4     50   0   0   0   1

我知道如何在SAS中执行此操作,但无法使用R找到解决方案。非常感谢您的帮助

这里有一个带
表的
基本R
选项

library('tidyr')
df1 <- data.frame(ID=c(1:4), Amount=c(100, 150, 75, 50), 
                  Month=c("Jan", "Feb", "Mar", "Apr"))
df1$ID <- 1
df1 <- spread(df1 , Month, ID, fill=0)
df1
cbind(df1, as.data.frame.matrix(table(lapply(df1[-1], 
                         function(x) factor(x, levels = unique(x))))))

这是一个带有
表的
基本R
选项

cbind(df1, as.data.frame.matrix(table(lapply(df1[-1], 
                         function(x) factor(x, levels = unique(x))))))

如果没有安装
tidyr
,请尝试
install.packages('tidyr')
如果没有安装
tidyr
,请尝试
install.packages('tidyr')
cbind(df1, as.data.frame.matrix(table(lapply(df1[-1], 
                         function(x) factor(x, levels = unique(x))))))