之前寫過一篇文章是往文本文件中不斷寫入數據時用到了append=T,
今天用到append()
1.如何往list某列末尾添加數據?
直接用append(某list,要寫入的數據)
append(x, values, after = length(x))
Arguments
x |
the vector to be modified. |
values |
to be included in the modified vector. 計劃貼入的對象 |
after |
a subscript, after which the values are to be appended. 表示想在x中貼的位置 |
舉例:
例一:
> L1
$p1
[1] 2 3 4 5
$p2
[1] 10 11 12 13 14 15
> append(L1$p1,13)
[1] 2 3 4 5 13
例二:
> append(1:5, 0:1, after = 3)
[1] 1 2 3 0 1 4 5
2. list中查找列名
使用names(sapply(list, names))
舉例:
> mylist <- list("a"=c(1,2),"b"=c(3,4),"c"=c(5,6))
> mylist
$a
[1] 1 2
$b
[1] 3 4
$c
[1] 5 6
> names(sapply(mylist, names))
[1] "a" "b" "c"
> sapply(mylist, names)
$a
NULL
$b
NULL
$c
NULL
參考鏈接: https://stat.ethz.ch/pipermail/r-help/2011-January/265633.html
3. 查找某個變量名是否已經存在於List中
方法一:match(變量名,list所有變量集)
舉例:
> match("a",nameslist)
[1] 1
方法二: is.element(變量名,list所有變量集)
舉例:
> is.element('a',nameslist)
[1] TRUE
如何將一個動態的變量名賦給list做列名?
舉例:
> names<-ru1405_1021$BUY1[1]
> names
[1] 20625
> test<-list(names=ru1405_1021$BUY1[1])
> test
$names
[1] 20625
如果想把ru1405_1021$BUY1[i]作爲test的列名,
如果直接增加列,結果如下,杯具
> test$ru1405_1021$BUY1[2]<-ru1405_1021$BUY1[2]
> test
$names
[1] 20625
$ru1405_1021
$ru1405_1021$BUY1
[1] NA 20620
> name<-ru1405_1021$BUY1[2]
> test$name<-ru1405_1021$BUY1[2]
> test
$names
[1] 20625
$ru1405_1021
$ru1405_1021$BUY1
[1] NA 20620
$name
[1] 20620
List列表其他相關操作
1.構造一個list
my.lst<-list(stud.id=3353,
stud.name="john",
stud.marks=c(14.3,12,15))
2. 索引
my.lst[[1]]
或者my.lst$stud.id
3. 擴展列表
my.lst$parents.names<-c("Anna","Mike")
4. 檢查list成分個數
length(my.lst)
5. 剔除list成分
my.lst<-my.lst[-5]
6.合併list
other<-list(age=19,sex="male")
lst<-c(my.lst,other)
7. 將list中的所有元素轉爲向量元素
unlist(my.lst)