將元素加入 list
建立好 list 之後,並不是一成不變。你想要的時候,隨時都能加入新元素!假設你想把朋友 Dan 最喜歡的電影加入清單。你可以像替資料框新增欄位一樣,用 $ 來做到。
my_list$dans_movie <- "StaR Wars"
my_list
$my_words
[1] "I <3 R"
$my_numbers
[1] 42 24
$dans_movie
[1] "StaR Wars"
你也可以用 c() 把另一個元素加入 list:c(my_list, dans_movie = "StaR Wars")。如果你想一次加入多個元素,這會很方便。
本練習屬於課程
R for Finance 入門
練習說明
- 對於你的
portfolio,另一個有用的資訊是變數weight,用來表示你在 Apple 和 IBM 的投資比重。請正確填入___,讓你在 Apple 投資 20% 、在 IBM 投資 80%。記得要用「小數」而不是百分比! - 列印
portfolio以查看weight元素。 - 你可以像用
$加入元素一樣,改變 list 中的資料。建立weight,讓在 Apple 投資 30% 、在 IBM 投資 70%。 - 再次列印
portfolio檢視你的變更。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Add weight: 20% Apple, 80% IBM
portfolio$___ <- c(apple = ___, ibm = ___)
# Print portfolio
# Change the weight variable: 30% Apple, 70% IBM
portfolio$___ <- c(apple = ___, ibm = ___)
# Print portfolio to see the changes