write.table은 행 이름이있을 때 원하지 않는 선행 빈 열을 헤더에 씁니다.
이 예를 확인하십시오.
> a = matrix(1:9, nrow = 3, ncol = 3, dimnames = list(LETTERS[1:3], LETTERS[1:3]))
> a
A B C
A 1 4 7
B 2 5 8
C 3 6 9
테이블이 올바르게 표시됩니다. 파일에 쓰는 방법에는 두 가지가 있습니다.
write.csv(a, 'a.csv')
예상대로 제공됩니다.
"","A","B","C"
"A",1,4,7
"B",2,5,8
"C",3,6,9
그리고 write.table(a, 'a.txt')
어떤 나사
"A" "B" "C"
"A" 1 4 7
"B" 2 5 8
"C" 3 6 9
실제로, 빈 탭이 없습니다 .... 다운 스트림에 대한 엉덩이에 고통입니다. 버그입니까, 기능입니까? 해결 방법이 있습니까? (이외 write.table(cbind(rownames(a), a), 'a.txt', row.names=FALSE
)
건배, 야닉
인용 ?write.table
, 섹션 CSV 파일 :
기본적으로 행 이름 열에는 열 이름이 없습니다. 만약
col.names = NA
과row.names = TRUE
빈 열 이름은 스프레드 시트에서 읽을 수있는 CSV 파일에 사용되는 규칙 인 추가됩니다.
그래서 당신은해야합니다
write.table(a, 'a.txt', col.names=NA)
그리고 당신은
"" "A" "B" "C"
"A" 1 4 7
"B" 2 5 8
"C" 3 6 9
@Marek에 대한 약간의 수정은 매우 유용한 답변입니다. rownames 열에 헤더를 추가합니다. 임시로 rownames를 data.frame의 첫 번째 열로 추가하고 실제 행 이름을 무시하고 작성합니다.
> a = matrix(1:9, nrow = 3, ncol = 3, dimnames = list(LETTERS[1:3], LETTERS[1:3]))
> write.table(data.frame("H"=rownames(a),a),"a.txt", row.names=FALSE)
그리고 당신은
"H" "A" "B" "C"
"A" 1 4 7
"B" 2 5 8
"C" 3 6 9
tidyverse (dplyr 등) 에서 작업하는 사람이라면 tibble 패키지 의 rownames_to_column()
함수를 사용하여 row.names를 열로 쉽게 변환 할 수 있습니다. 예 :
library('tibble')
a = as.data.frame(matrix(1:9, nrow=3, ncol=3,
dimnames=list(LETTERS[1:3], LETTERS[1:3])))
a %>% rownames_to_column('my_id')
my_id A B C
1 A 1 4 7
2 B 2 5 8
3 C 3 6 9
이 row.names=FALSE
옵션 을의 옵션 과 결합하면 write.table()
모든 열에 대한 헤더 이름이 출력됩니다.
행렬을 저장할 때 동일한 문제가 발생 write.table()
하고 row.names 열을 유지하려는 경우 실제로 매우 간단한 솔루션이 있습니다.
write.table(matrix,file="file.csv",quote=F,sep=";", row.names=T
col.names=c("row_name_col;val1_col","val2_col"))
By doing that you're basically tricking the write.table
function into creating a header label for the row.names column. The resulting .csv file would look like this:
row_name_col;val1_col;val2_col
row1;1;4
row2;2;5
row3;3;6
I revised a simple function from @mnel, which adds flexibility by using connections. Here is the function:
my.write <- function(x, file, header, f = write.csv, ...){
# create and open the file connection
datafile <- file(file, open = 'wt')
# close on exit
on.exit(close(datafile))
# if a header is defined, write it to the file (@CarlWitthoft's suggestion)
if(!missing(header)) {
writeLines(header,con=datafile, sep='\t')
writeLines('', con=datafile, sep='\n')
}
# write the file using the defined function and required addition arguments
f(x, datafile,...)
}
You can specify the function to be 'write.table', 'write.csv', 'write.delim' etc.
Cheers!
'developer tip' 카테고리의 다른 글
비틀어 진 파이썬 : 어디서부터 시작해야할까요? (0) | 2020.09.25 |
---|---|
ThreadLocal 변수의 성능 (0) | 2020.09.25 |
DataFrame의 문자열이지만 dtype은 객체입니다. (0) | 2020.09.25 |
R에서 %> % 함수는 무엇을 의미합니까? (0) | 2020.09.25 |
MySQL 사용자 이름과 암호를 디 컴파일로부터 보호하려면 어떻게해야합니까? (0) | 2020.09.25 |