我有一个如下数据框,
id sex age trt.1 response.1 trt.2 response.2
1 1 <NA> NA A 1 B 1
2 2 <NA> NA A 1 B 1
3 3 <NA> NA A 1 B 1
4 4 M 28 A 1 B 1
5 5 F 39 A 1 B 1
6 6 M 47 A 1 B 1
我想将其更改为
id sex age times response
1 1 <NA> NA A 1
2 1 <NA> NA B 1
3 2 <NA> NA A 1
4 2 <NA> NA B 1
.
.
.
.
我尝试了以下内容,
reshape(merged, idvar = "id", varying = list(4:7), v.names="response", times=c("A","B"), direction="long")
但是我收到了这个错误,
Error in reshapeLong(data, idvar = idvar, timevar = timevar, varying = varying, :
'times' is wrong length
我尝试了时间= C(“A”,“B”,“A”,“B”)那时我得到输出,但原始数据帧是70行,输出应该是140行,但是当我用这个我得到280行是错的。任何人都可以帮我解决我的错误吗?
答案 0 :(得分:2)
这是你期待的吗?您只需要将Dim UserInput
UserInput = InputChecker
' You can reuse the accepted user input
If Length = 8 Then Wscript.Echo "User input: """ & UserInput & """"
Function InputChecker
Dim Input, Length
Do
Input = InputBox("Enter your name","Enter your name (must be 8 characters)")
If Input = False Then Exit Do
Input = Trim(Input) ' Remove spaces at front and back
Length = Len(Input)
If Length <> 8 Then
If Msgbox("Input must be 8 characters, not " & Len(Input) & "!",5+48,"INPUT LENGTH ERROR") = 2 Then
Input = "" ' Reset it to empty string
Exit Do
End If
End If
Loop Until Length = 8
InputChecker = Input
End Function
更改为varying = list(4:7)
,因为您实际上正在同时融化两件。
varying = list(c(4,6), c(5,7))
答案 1 :(得分:0)
重塑非常棒,但我真的不明白为什么你需要在这种情况下使用它。
text = "id sex age trt.1 response.1 trt.2 response.2
1 1 <NA> NA A 1 B 1
2 2 <NA> NA A 1 B 1
3 3 <NA> NA A 1 B 1
4 4 M 28 A 1 B 1
5 5 F 39 A 1 B 1
6 6 M 47 A 1 B 1"
data <- read.table(text = text)
result1 <- data[, c("id", "sex", "age", "trt.1", "response.1")]
result2 <- data[, c("id", "sex", "age", "trt.2", "response.2")]
names(result1) <- c("id", "sex", "age", "trt", "response")
names(result2) <- c("id", "sex", "age", "trt", "response")
result <- rbind(result1, result2)
这是输出:
id sex age trt response
1 1 <NA> NA A 1
2 2 <NA> NA A 1
3 3 <NA> NA A 1
4 4 M 28 A 1
5 5 F 39 A 1
6 6 M 47 A 1
11 1 <NA> NA B 1
...
答案 2 :(得分:0)
这是最简单的方法:
library(dplyr)
library(tidyr)
data %>%
gather(variable, value,
trt.1:response.2) %>%
separate(variable, c("variable", "number")) %>%
spread(variable, value)
答案 3 :(得分:0)
我们可以使用melt
中的library(data.table)
measure
,其中pattern
个参数可以带有多个library(data.table)#v1.9.6+
melt(setDT(df2), measure=patterns('^trt', 'response'), value.name=c('times', 'response'))
# id sex age variable times response
# 1: 1 <NA> NA 1 A 1
# 2: 2 <NA> NA 1 A 1
# 3: 3 <NA> NA 1 A 1
# 4: 4 M 28 1 A 1
# 5: 5 F 39 1 A 1
# 6: 6 M 47 1 A 1
# 7: 1 <NA> NA 2 B 1
# 8: 2 <NA> NA 2 B 1
# 9: 3 <NA> NA 2 B 1
#10: 4 M 28 2 B 1
#11: 5 F 39 2 B 1
#12: 6 M 47 2 B 1
Width:50%;